diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..5bb86c7 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,57 @@ +name: Gradle CI + +on: + push: + branches: + - '**' + paths-ignore: + - 'README.md' + - 'LICENSE' + - '.gitignore' + pull_request: + branches: + - '**' + paths-ignore: + - 'README.md' + - 'LICENSE' + - '.gitignore' + workflow_dispatch: +jobs: + build: + strategy: + matrix: + os: [ ubuntu-latest, windows-latest ] + runs-on: ${{ matrix.os }} + name: Build with gradle + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Set up Java 17 + uses: actions/setup-java@v4 + with: + java-version: 17 + distribution: temurin + - name: Set up Java 21 + uses: actions/setup-java@v4 + with: + java-version: 21 + distribution: temurin + - uses: actions/cache@v3 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + ./.gradle/loom-cache + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} + restore-keys: | + ${{ runner.os }}-gradle- + - name: Grant execute permission for gradlew + if: ${{ runner.os != 'Windows' }} + run: chmod +x ./gradlew + - name: Build with Gradle + run: ./gradlew build --no-daemon + - uses: actions/upload-artifact@v4 + with: + name: artifact-${{ matrix.os }} + path: | + **/build/libs/ \ No newline at end of file diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..e17c074 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,44 @@ +name: Publish Release + +on: + push: + branches: + - '*/prod' + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + name: Publish with gradle + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Set up Java 17 + uses: actions/setup-java@v4 + with: + java-version: 17 + distribution: temurin + - name: Set up Java 21 + uses: actions/setup-java@v4 + with: + java-version: 21 + distribution: temurin + - uses: actions/cache@v3 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + ./.gradle/loom-cache + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} + restore-keys: | + ${{ runner.os }}-gradle- + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Publish + run: ./gradlew publish publishMods + env: + CURSEFORGE_TOKEN: ${{secrets.CURSEFORGE}} + MODRINTH_TOKEN: ${{secrets.MODRINTH}} + GH_TOKEN: ${{secrets.GITHUB_TOKEN}} + DISCORD_WEBHOOK: ${{secrets.DISCORD_WEBHOOK}} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..77f4cee --- /dev/null +++ b/.gitignore @@ -0,0 +1,44 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ +run +logs + +### IntelliJ IDEA ### +.idea/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Kotlin ### +.kotlin + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..66ed69a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Beta 1.2 + +## What’s New +- **Supports Minecraft 1.20.1 → 1.21.8** +- **Works on NeoForge and Fabric** (Forge coming later) +- **Rewritten in Kotlin** for smoother performance and fewer bugs +- **Built‑in widget system** for better stability without extra libraries \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f51db25 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 CalculatorsTeam + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..54fb894 --- /dev/null +++ b/README.md @@ -0,0 +1,63 @@ +# DynamicPack +A mod that will monitor the current version of your resource pack and download automatically! + +![https://img.shields.io/badge/Enviroment-Client-purple](https://img.shields.io/badge/Enviroment-Client-purple) +[![Static Badge](https://img.shields.io/badge/Github-gray?logo=github) +](https://github.com/CalculatorsTeam/DynamicPack) + +[![Java CI with Gradle](https://github.com/CalculatorsTeamAdamCalculator/DynamicPack/actions/workflows/gradle.yml/badge.svg)](https://github.com/AdamCalculator/DynamicPack/actions/workflows/gradle.yml) + +[![Banner](https://api.mcbanners.com/banner/saved/wveMrFfPsqwXbV.png)](https://modrinth.com/mod/dynamicpack) + +## Documentation +[**Available here**](https://github.com/CalculatorsTeam/DynamicPack/wiki) + +## Packs using it mod +* [Better Tables](https://modrinth.com/resourcepack/bettertables) +* [CursedEveryday (github)](https://github.com/AdamCalculator/CursedEveryday/releases/tag/day4) +* [ModsRU](https://modrinth.com/resourcepack/mods-ru) +* [zelda-music](https://modrinth.com/resourcepack/zelda-music) +* [PawTotems (smp) (github)](https://github.com/1NFERR/PawTotems/) +* [SPPack (smp) (github)](https://github.com/aladairmaxwell/SP) +* [Essentially Tweaked](https://modrinth.com/resourcepack/essentially-tweaked) +* [Vanilla Leaves](https://modrinth.com/resourcepack/vanilla-leaves) + +## Plans +The mod is planned to support **any bootloader** and any version, but I don't have enough time right now. **I'm always happy to see new contributors!** + +## How it works +Resource pack developers need to create a `dynamicmcpack.json` file inside the resource pack, which will save some information, and the mod will update when the game starts if resource pack files are required. + +## For users +Install and it will automatically update supported resource packs. + +⚠️ Since the mod is being actively developed, it is not yet possible to check resource packs for updates, but this will be added in the future. + + +## For developers +If you want your package to update itself from **Modrinth**, you need to add the `dynamicmcpack.json` file to the following content: +```json5 +{ + "current": { + "version_number": "7.1" // version of the current pack + }, + "remote": { + "game_version": "1.21.1", // game version + "modrinth_project_id": "better-leaves", // your project identifier + "type": "modrinth" + }, + "formatVersion": 1 +} +``` +**⚠️⚠️⚠️ JSON Specification not support //comments! Delete it before use.** + +You can validate your JSON [here](https://jsonformatter.curiousconcept.com/#) + + +For other features (dynamic repos) visit [github wiki!](https://github.com/CalculatorsTeam/DynamicPack/wiki) + + +## Donate +The project is completely free and open under the MIT licence. You can help original author by donating ❤️ + +**Bitcoin:** `bc1qpc0q9ym7rnfatdh43c4jyf68znj8x2jae5j4cz` diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..7bf9fdd --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,289 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import java.util.Locale + +plugins { + id("dev.kikugie.stonecutter") + id("dev.isxander.modstitch.base") + id("dev.isxander.modstitch.publishing") + kotlin("jvm") + `maven-publish` +} + +// ========== Versions & Project Info ========== +val mcVersion: String by project +val versionWithoutMC = property("modVersion")!!.toString() + +val isDev = resolveProp("isDev") +val isAlpha = "-a" in versionWithoutMC +val isBeta = "-b" in versionWithoutMC + +val isFabric = modstitch.isLoom +val isNeoforge = modstitch.isModDevGradleRegular +val isForge = modstitch.isModDevGradleLegacy +val isForgeLike = modstitch.isModDevGradle + +val loader = when { + isFabric -> "fabric" + isNeoforge -> "neoforge" + isForge -> "forge" + else -> error("Unknown loader") +} + +val javaTargetVersion = if (stonecutter.eval(mcVersion, ">1.20.4")) 21 else 17 +val resolvedModId = resolveProp("modId") ?: error("modId is required") +val gitHash = gitHash() + +// ========== ModStitch Setup ========== +modstitch { + minecraftVersion = mcVersion + javaVersion = javaTargetVersion + + if (!isForge) { + unitTesting() + } + + kotlin { + jvmToolchain(javaVersion.get()) + compilerOptions.jvmTarget.set(JvmTarget.fromTarget(javaVersion.get().toString())) + } + + parchment { + mappingsVersion = resolveProp("parchment.version") + minecraftVersion = resolveProp("parchment.minecraft") + } + + metadata { + modId = resolvedModId + modName = resolveProp("modName") + modVersion = "$versionWithoutMC${if (isAlpha || isBeta) "." else "+"}${stonecutter.current.project}${if (isDev?.lowercase(Locale.getDefault()) == "true" || isDev == "1") "-DEV-$gitHash" else ""}" + modGroup = resolveProp("modGroup") + modDescription = resolveProp("modDescription") + modLicense = resolveProp("modLicense") + modAuthor = resolveProp("modAuthor") + + replacementProperties.put( + "pack_format", when (mcVersion) { + "1.19.2" -> 9 + "1.20.1" -> 15 + "1.21.1" -> 34 + "1.21.3" -> 57 + "1.21.4" -> 61 + "1.21.5" -> 71 + "1.21.8" -> 81 + else -> throw IllegalArgumentException("Please store the resource pack version for $mcVersion in build.gradle.kts! https://minecraft.wiki/w/Pack_format") + }.toString() + ) + + replacementProperties.put("gitHead", gitHash) + + // replacementProperties DSL + fun setReplace(key: String, property: String) { + resolveProp(property)?.let { replacementProperties.put(key, it) } + } + + setReplace("github", "githubProject") + setReplace("mc", "meta.mcDep") + setReplace("fabricLoader", "deps.fabricLoader") + setReplace("fabricLangKotlin", "deps.fabricLangKotlin") + setReplace("fapi", "deps.fabricApi") + } + + loom { + resolveProp("deps.fabricLoader")?.let { fabricLoaderVersion = it } + } + + moddevgradle { + resolveProp("deps.neoforge")?.let { neoForgeVersion = it } + resolveProp("deps.forge")?.let { forgeVersion = it } + defaultRuns() + + configureNeoForge { + runs.all { + jvmArguments.add("-Dmixin.debug.export=true") + } + } + + modstitch.onEnable { + tasks.named("createMinecraftArtifacts") { + dependsOn("stonecutterGenerate") + } + } + } + + mixin { + addMixinsToModManifest = true + configs.register(resolvedModId) + } +} + +// ========== Stonecutter ========== +stonecutter { + constants { + put("fabric", isFabric) + put("neoforge", isNeoforge) + put("forge", isForge) + put("forgelike", isForgeLike) + } + + dependencies { + put("fapi", resolveProp("deps.fabricApi") ?: "0.0.0") + } +} + +// ========== Dependencies ========== +dependencies { + if (isFabric) { + modstitchModImplementation("net.fabricmc.fabric-api:fabric-api:${resolveProp("deps.fabricApi")}") + modstitchModImplementation("net.fabricmc:fabric-language-kotlin:${resolveProp("deps.fabricLangKotlin")}") + + modstitchModImplementation("com.terraformersmc:modmenu:${resolveProp("deps.modmenu")}") + } + + if (isNeoforge) { + modstitchModRuntimeOnly("thedarkcolour:kotlinforforge-neoforge:${resolveProp("deps.kotlinForForge")}") + } + + if (isForge) { + modstitchModRuntimeOnly("thedarkcolour:kotlinforforge:${resolveProp("deps.kotlinForForge")}") + compileOnly("org.jetbrains:annotations:20.1.0") + } + + modstitchModApi("dev.isxander:yet-another-config-lib:${resolveProp("deps.yacl")}") { + exclude(group = "thedarkcolour") + } +} + +msPublishing { + maven { + repositories { + mavenLocal() + } + } + + fun versionList(prop: String) = findProperty(prop)?.toString() + ?.split(',') + ?.map { it.trim() } + ?: emptyList() + + val stableMCVersions = versionList("pub.stableMC") + + mpp { + displayName.set("$versionWithoutMC for $loader $mcVersion") + + changelog.set( + file("CHANGELOG.md") + .takeIf { it.exists() } + ?.readText() + ) + + type = when { + isAlpha -> ALPHA + isBeta -> BETA + else -> STABLE + } + + modLoaders.add(loader) + + val modrinthId: String by project + if (modrinthId.isNotBlank() && hasProperty("MODRINTH_TOKEN")) { + modrinth { + projectId.set(modrinthId) + accessToken.set(findProperty("MODRINTH_TOKEN")?.toString()) + minecraftVersions.addAll(stableMCVersions) + minecraftVersions.addAll(versionList("pub.modrinthMC")) + + if (isFabric) { + requires { slug.set("fabric-language-kotlin") } + } + if (isForgeLike) { + requires { slug.set("kotlin-for-forge") } + } + optional { slug.set("yacl") } + } + } + + val curseforgeId: String by project + if (curseforgeId.isNotBlank() && hasProperty("CURSEFORGE_TOKEN")) { + curseforge { + projectId = curseforgeId + projectSlug = findProperty("curseforgeSlug")?.toString() ?: error("curseforgeSlug property not found") + accessToken = findProperty("CURSEFORGE_TOKEN")?.toString() + minecraftVersions.addAll(stableMCVersions) + minecraftVersions.addAll(versionList("pub.curseMC")) + + if (isFabric) { + requires { slug.set("fabric-language-kotlin") } + } + if (isForgeLike) { + requires { slug.set("kotlin-for-forge") } + } + optional { slug.set("yacl") } + } + } + + val githubProject: String by project + if (githubProject.isNotBlank() && hasProperty("GH_TOKEN")) { + github { + repository.set(githubProject) + accessToken.set(findProperty("GH_TOKEN")?.toString()) + commitish.set(gitBranch()) + } + } + + if (hasProperty("DISCORD_WEBHOOK")) { + discord { + username.set("DynamicPack Updates") + webhookUrl.set(findProperty("DISCORD_WEBHOOK")?.toString()) + content.set(changelog) + } + } + + dryRun = true + } +} + +// ========== Tasks ========== +tasks { + withType().configureEach { + compilerOptions { + jvmTarget = modstitch.javaVersion.map { JvmTarget.fromTarget(it.toString()) } + } + dependsOn("stonecutterGenerate") + } + + named("generateModMetadata") { + dependsOn("stonecutterGenerate") + } + + if (isForge) { + named("test") { + enabled = false + } + } +} + +// ========== Helpers ========== +fun resolveProp(property: String): String? = + System.getenv(property)?.takeIf { it.isNotBlank() } + ?: findProperty(property)?.toString()?.takeIf { it.isNotBlank() } + +fun gitHash(): String { + val process = ProcessBuilder("git", "rev-parse", "--short", "HEAD") + .redirectErrorStream(true) // combine stdout + stderr + .start() + + val text = process.inputStream.bufferedReader().use { it.readText() } + + return text.trim() +} + +fun gitBranch(): String { + val process = ProcessBuilder("git", "rev-parse", "--abbrev-ref", "HEAD") + .redirectErrorStream(true) // объединяем stdout и stderr + .start() + + val text = process.inputStream.bufferedReader().use { it.readText() } + + return text.trim() +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..e8eac9f --- /dev/null +++ b/gradle.properties @@ -0,0 +1,19 @@ +isDev=false +modId=dynamicpack +modName=DynamicPack +modDescription=Adds auto-update support for resource packs +modLicense=MIT +modAuthor=AdamCalculator, Riflusso +modGroup=com.calculatorsteam +modVersion=1.2-b + +modrinthId=IT6fZgjc +curseforgeSlug=dynamicpack +curseforgeId=1356312 +githubProject=CalculatorsTeam/DynamicPack + +deps.fabricLoader=0.17.2 +deps.fabricLangKotlin=1.13.6+kotlin.2.2.20 + +org.gradle.jvmargs=-Xmx4G +org.gradle.parallel=true \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..2e11132 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/modstitch.accesswidener b/modstitch.accesswidener new file mode 100644 index 0000000..cf997b3 --- /dev/null +++ b/modstitch.accesswidener @@ -0,0 +1,3 @@ +accessWidener v1 named +accessible method net/minecraft/client/gui/components/AbstractSelectionList getRowTop (I)I +accessible class net/minecraft/server/packs/FilePackResources$SharedZipFileAccess diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..288a065 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,35 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + maven("https://maven.fabricmc.net/") + maven("https://maven.architectury.dev") + maven("https://maven.neoforged.net/releases/") + maven("https://maven.minecraftforge.net/") + maven("https://maven.kikugie.dev/releases") + maven("https://maven.kikugie.dev/snapshots") + maven("https://maven.isxander.dev/releases") + } +} + +plugins { + id("dev.kikugie.stonecutter") version "0.7.10" +} + +stonecutter { + kotlinController = true + centralScript = "build.gradle.kts" + + create(rootProject) { + fun mc(mcVersion: String, name: String = mcVersion, loaders: Iterable) = + loaders.forEach { version("$name-$it", mcVersion) } + + mc("1.20.1", loaders = listOf("fabric")) + mc("1.21.1", loaders = listOf("fabric", "neoforge")) + mc("1.21.3", loaders = listOf("fabric", "neoforge")) + mc("1.21.4", loaders = listOf("fabric", "neoforge")) + mc("1.21.5", loaders = listOf("fabric", "neoforge")) + mc("1.21.8", loaders = listOf("fabric", "neoforge")) + } +} +rootProject.name = "DynamicPack" \ No newline at end of file diff --git a/src/main/java/com/calculatorsteam/dynamicpack/accessor/FilePackResourcesAccessor.java b/src/main/java/com/calculatorsteam/dynamicpack/accessor/FilePackResourcesAccessor.java new file mode 100644 index 0000000..b34202c --- /dev/null +++ b/src/main/java/com/calculatorsteam/dynamicpack/accessor/FilePackResourcesAccessor.java @@ -0,0 +1,9 @@ +package com.calculatorsteam.dynamicpack.accessor; + +import java.io.File; + +public interface FilePackResourcesAccessor { + boolean dynamicpack$isClosed(); + File dynamicpack$getFile(); + void dynamicpack$close(); +} \ No newline at end of file diff --git a/src/main/java/com/calculatorsteam/dynamicpack/mixins/FilePackResourcesMixin.java b/src/main/java/com/calculatorsteam/dynamicpack/mixins/FilePackResourcesMixin.java new file mode 100644 index 0000000..7676b35 --- /dev/null +++ b/src/main/java/com/calculatorsteam/dynamicpack/mixins/FilePackResourcesMixin.java @@ -0,0 +1,58 @@ +package com.calculatorsteam.dynamicpack.mixins; + +import com.calculatorsteam.dynamicpack.accessor.FilePackResourcesAccessor; +import com.calculatorsteam.dynamicpack.util.LockUtils; +import net.minecraft.server.packs.FilePackResources; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.io.File; +import java.util.zip.ZipFile; + +@Mixin(FilePackResources./*? if >=1.21 {*/SharedZipFileAccess./*?}*/class) +public abstract class FilePackResourcesMixin implements FilePackResourcesAccessor { + + @Unique private boolean dynamicpack$opened; + + @Shadow public abstract void close(); + + @Shadow @Final + //? if < 1.21 + /*private*/ + File file; + + @Inject(at = @At("RETURN"), method = "getOrCreateZipFile") + public void dynamicpack$return$getOrCreateZipFile(CallbackInfoReturnable cir) { + ZipFile ret = cir.getReturnValue(); + if (ret != null) { + dynamicpack$opened = true; // теперь действительно открыт + LockUtils.addFileToOpened(this); + } + } + + @Inject(at = @At("RETURN"), method = "close") + public void dynamicpack$return$close(CallbackInfo ci) { + dynamicpack$opened = false; + } + + @Override + public boolean dynamicpack$isClosed() { + return !dynamicpack$opened; + } + + @Override + public File dynamicpack$getFile() { + return file; + } + + @Override + public void dynamicpack$close() { + close(); + } +} \ No newline at end of file diff --git a/src/main/java/com/calculatorsteam/dynamicpack/mixins/MinecraftClientMixin.java b/src/main/java/com/calculatorsteam/dynamicpack/mixins/MinecraftClientMixin.java new file mode 100644 index 0000000..05f3923 --- /dev/null +++ b/src/main/java/com/calculatorsteam/dynamicpack/mixins/MinecraftClientMixin.java @@ -0,0 +1,18 @@ +package com.calculatorsteam.dynamicpack.mixins; + +import com.calculatorsteam.dynamicpack.client.PackMixinHelper; +import net.minecraft.client.Minecraft; +import net.minecraft.client.main.GameConfig; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + + +@Mixin(Minecraft.class) +public abstract class MinecraftClientMixin { + @Inject(at = @At("RETURN"), method = "") + private void dynamicpack$initCheck(GameConfig args, CallbackInfo ci) { + PackMixinHelper.minecraftInitReturned(); + } +} diff --git a/src/main/java/com/calculatorsteam/dynamicpack/mixins/PackRepositoryMixin.java b/src/main/java/com/calculatorsteam/dynamicpack/mixins/PackRepositoryMixin.java new file mode 100644 index 0000000..957b5c2 --- /dev/null +++ b/src/main/java/com/calculatorsteam/dynamicpack/mixins/PackRepositoryMixin.java @@ -0,0 +1,61 @@ +package com.calculatorsteam.dynamicpack.mixins; + +import com.calculatorsteam.dynamicpack.DynamicPackMod; +import com.calculatorsteam.dynamicpack.client.GameStartSyncing; +import com.calculatorsteam.dynamicpack.platform.VersionFunctions; +import com.calculatorsteam.dynamicpack.util.log.Out; +import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.Minecraft; +import net.minecraft.server.packs.repository.PackRepository; +import org.lwjgl.glfw.GLFW; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(PackRepository.class) +public class PackRepositoryMixin { + + /** + * For freeze resource pack loading (only in game starting) until DynamicPack update it + */ + @Inject(at = @At("HEAD"), method = "reload") + private void dynamicpack$reload(CallbackInfo ci) { + // do nothing if minecraft initialized + if (DynamicPackMod.getInstance().isMinecraftInitialized()) { + return; + } + + Minecraft client = Minecraft.getInstance(); + GameStartSyncing syncing = DynamicPackMod.getGameStartSyncing(); + if (!syncing.isLockSupported()) { + return; + } + + if (syncing.getLockResourcesLoading()) { + syncing.startGameLocking(); + while (!client.getWindow().shouldClose() && syncing.getLockResourcesLoading()) { + if (!syncing.lockedTick()) { + break; + } + + try { + VersionFunctions.applyModelViewMatrix(); + VersionFunctions.clearColor(0.074f + (((float)syncing.getPercentage() / 100f)), 0.04f, (float) (0.24f + (Math.sin(System.currentTimeMillis() / 300f) / 2)), 1f); + VersionFunctions.clear(16640); + GLFW.glfwSwapBuffers(client.getWindow().getWindow()); + + } catch (Exception e) { + Out.error("Error while manipulations with OpenGL", e); + } + + try { + Thread.sleep(50); + } catch (InterruptedException ignored) { + } + } + syncing.endGameLocking(); + } + } +} + diff --git a/src/main/java/com/calculatorsteam/dynamicpack/mixins/ResourcePackEntryMixin.java b/src/main/java/com/calculatorsteam/dynamicpack/mixins/ResourcePackEntryMixin.java new file mode 100644 index 0000000..8cde469 --- /dev/null +++ b/src/main/java/com/calculatorsteam/dynamicpack/mixins/ResourcePackEntryMixin.java @@ -0,0 +1,96 @@ +package com.calculatorsteam.dynamicpack.mixins; + +import com.calculatorsteam.dynamicpack.client.gui.widget.DynamicPackResourcePackEntryWidget; +import com.calculatorsteam.dynamicpack.client.gui.widget.ResourcePackEntryWidget; +import com.calculatorsteam.dynamicpack.platform.VersionFunctions; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.packs.TransferableSelectionList; +import net.minecraft.client.gui.screens.packs.PackSelectionModel; +import net.minecraft.resources.ResourceLocation; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(TransferableSelectionList.PackEntry.class) +public abstract class ResourcePackEntryMixin { + + @Shadow + protected abstract boolean showHoverOverlay(); + + @Shadow + @Final + private PackSelectionModel.Entry pack; + @Shadow + @Final + private TransferableSelectionList parent; + + @Unique + int dynamicpack$selected = -1; + @Unique + private Boolean fold; + @Unique + int dynamicpack$foldTicks = 0; + @Unique + private static final int maxFoldTicks = 10; + @Unique + private static final ResourcePackEntryWidget DYNAMIC_WIDGET = new DynamicPackResourcePackEntryWidget(); + + @Inject(at = @At("TAIL"), + method = "render(Lnet/minecraft/client/gui/GuiGraphics;IIIIIIIZF)V") + private void render(GuiGraphics context, int index, int y, int x, int entryWidth, int entryHeight, + int mouseX, int mouseY, boolean hovered, float tickDelta, CallbackInfo info) { + int prevMargin = 0; + /*? if >=1.21 {*/ + int deltaX = 3 + (VersionFunctions.maxScrollAmount(parent) > 0 ? 7 : 0); + /*?} else {*/ + /*int deltaX = 8 + (parent.getMaxScroll() > 0 ? 7 : 0); + *//*?}*/ + boolean selectable = showHoverOverlay(); + dynamicpack$selected = -1; + if (dynamicpack$foldTicks == maxFoldTicks) { + /*? if >=1.21 {*/ + VersionFunctions.blitSprite(context, ResourceLocation.withDefaultNamespace("transferable_list/unselect"), + x + entryWidth - 16 - deltaX, y + entryWidth / 20 - 16, 16, 32); + /*?} else {*/ + /*context.blit(new ResourceLocation("textures/gui/resource_packs.png"), + x + entryWidth - 16 - deltaX, y + entryWidth / 20 - 16, 32.0F, 0.0F, 16, 32, 256, 256); + *//*?}*/ + } else { + ResourcePackEntryWidget widget = DYNAMIC_WIDGET; + if (widget.isVisible(pack, selectable)) { + deltaX += Math.max(prevMargin, widget.getXMargin(pack)); + int width = widget.getWidth(pack); + int height = widget.getHeight(pack, entryHeight); + int entryX = x + entryWidth - (deltaX + width) * (maxFoldTicks - dynamicpack$foldTicks) / maxFoldTicks; + int entryY = y + widget.getY(pack, entryHeight); + deltaX += width; + boolean widgetHovered = mouseX <= entryX + width && mouseX >= entryX && + mouseY <= entryY + height && mouseY >= entryY; + widget.render(pack, context, entryX, entryY, widgetHovered, tickDelta); + if (widgetHovered) dynamicpack$selected = 0; // фиксированный индекс + prevMargin = widget.getXMargin(pack); + } + } + if (fold == null) fold = deltaX > 48; + if (!fold) return; + int mouseRange = Math.max(10, deltaX) + 40; + if (mouseX >= x + entryWidth - mouseRange && mouseX <= x + entryWidth && + mouseY <= y + entryHeight && mouseY >= y) + dynamicpack$foldTicks = Math.max(dynamicpack$foldTicks - 1, 0); + else + dynamicpack$foldTicks = Math.min(dynamicpack$foldTicks + 1, maxFoldTicks); + } + + @Inject(method = "mouseClicked(DDI)Z", at = @At("RETURN"), cancellable = true) + private void dynamicpack$afterMouseClicked(double mouseX, double mouseY, int button, CallbackInfoReturnable cir) { + if (dynamicpack$selected != -1) { + cir.setReturnValue(false); + DYNAMIC_WIDGET.onClick(pack); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/calculatorsteam/dynamicpack/mixins/ResourcePackScreenMixin.java b/src/main/java/com/calculatorsteam/dynamicpack/mixins/ResourcePackScreenMixin.java new file mode 100644 index 0000000..2f0f7c4 --- /dev/null +++ b/src/main/java/com/calculatorsteam/dynamicpack/mixins/ResourcePackScreenMixin.java @@ -0,0 +1,20 @@ +package com.calculatorsteam.dynamicpack.mixins; + +import com.calculatorsteam.dynamicpack.client.PackMixinHelper; +import net.minecraft.client.gui.screens.packs.PackSelectionScreen; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(PackSelectionScreen.class) +public class ResourcePackScreenMixin { + /** + * For auto-rescan packs + */ + @Inject(at = @At("RETURN"), method = "populateLists") + private void dynamicpack$updatePackLists(CallbackInfo ci) { + PackMixinHelper.updatePacksMinecraftRequest(); + } +} + diff --git a/src/main/java/com/calculatorsteam/dynamicpack/mixins/TitleScreenMixin.java b/src/main/java/com/calculatorsteam/dynamicpack/mixins/TitleScreenMixin.java new file mode 100644 index 0000000..7a39d15 --- /dev/null +++ b/src/main/java/com/calculatorsteam/dynamicpack/mixins/TitleScreenMixin.java @@ -0,0 +1,25 @@ +package com.calculatorsteam.dynamicpack.mixins; + +import com.calculatorsteam.dynamicpack.Constants; +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.TitleScreen; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(TitleScreen.class) +public class TitleScreenMixin { + @Inject(at = @At("TAIL"), method = "render") + public void dynamicpack$render(GuiGraphics guiGraphics, int i, int j, float f, CallbackInfo ci) { + if (Constants.DEBUG) { + int k = Mth.ceil(Math.abs(Math.sin(((double) System.currentTimeMillis()) / 350d)) * 255.0f) << 24; + guiGraphics.drawString(Minecraft.getInstance().font, Component.literal("DynamicPack mod is DEBUG").withStyle(ChatFormatting.BOLD).append(Component.literal(" use a release version for stable behavior").withStyle(ChatFormatting.YELLOW)), 2, guiGraphics.guiHeight() - 20, 0xFF2222 | k); + } + } +} + diff --git a/src/main/kotlin/com/calculatorsteam/dynamicpack/Constants.kt b/src/main/kotlin/com/calculatorsteam/dynamicpack/Constants.kt new file mode 100644 index 0000000..3d5fe84 --- /dev/null +++ b/src/main/kotlin/com/calculatorsteam/dynamicpack/Constants.kt @@ -0,0 +1,163 @@ +package com.calculatorsteam.dynamicpack + +import com.calculatorsteam.dynamicpack.util.log.Out +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import java.io.IOException +import java.net.URI +import java.net.URISyntaxException + +object Constants { + // DISABLE ALL DEBUG IN OFFICIAL RELEASES + const val DEBUG: Boolean = false // Don't forget to disable in release + const val DEBUG_ALLOW_UNSECURE: Boolean = false + @JvmField var DEBUG_LOGS: Boolean = false + + const val VERSION_BUILD: Long = 50 + const val VERSION_NAME_MOD: String = "1.2" + /*? if >=1.21.6 {*/ + const val VERSION_NAME_BRANCH: String = "mc1.21.8" + /*?} else if >=1.21.5 {*/ + /*const val VERSION_NAME_BRANCH: String = "mc1.21.5" + *//*?} else if >=1.21.4 {*/ + /*const val VERSION_NAME_BRANCH: String = "mc1.21.4" + *//*?} else if >=1.21.2 {*/ + /*const val VERSION_NAME_BRANCH: String = "mc1.21.3" + *//*?} else if >=1.21 {*/ + /*const val VERSION_NAME_BRANCH: String = "mc1.21.1" + *//*?} else if >=1.20 {*/ + /*const val VERSION_NAME_BRANCH: String = "mc1.20.1" + *//*?}*/ + val VERSION_NAME: String = "$VERSION_NAME_MOD+$VERSION_NAME_BRANCH${if (DEBUG) "-debug" else ""}" + const val MOD_ID: String = "dynamicpack" + + // NOTE: for increase contact to mod developer. + val DYNAMIC_PACK_HTTPS_FILE_SIZE_LIMIT: Long = megabyte(8) // 8 MB + val MODRINTH_HTTPS_FILE_SIZE_LIMIT: Long = megabyte(1024) // 1 GB + val MOD_MODTINTH_API_LIMIT: Long = megabyte(8) // 8 MB + val GZIP_LIMIT: Long = megabyte(50) // 50 MB + val MOD_FILES_LIMIT: Long = megabyte(8) + const val MODRINTH_URL: String = "https://modrinth.com/mod/dynamicpack" + val NETWORK_STAT_RESET_LIMIT: Long = megabyte(3) + + // Settings + const val MAX_ATTEMPTS_TO_DOWNLOAD_FILE: Int = 3 + const val TEMP_DIR_NAME: String = "dynamicpack_f02ffd55_cd44_458a_8d58_e31b11313a53" + @JvmField var URLS_BUFFER_SIZE: Int = 1024 + + // const + const val HTTP_MINIMAL_HEADER_SIZE: Long = 24 + const val CLIENT_FILE: String = "dynamicmcpack.json" + const val MINECRAFT_META: String = "pack.mcmeta" + val UNKNOWN_PACK_MCMETA: String = """ + { + "pack": { + "pack_format": 17, + "description": "Unknown DynamicPack resource-pack..." + } + } + """.trimIndent() + + @JvmField val GSON: Gson = GsonBuilder().setPrettyPrinting().create() + + // --- Hosts --- + private val ALLOWED_HOSTS: MutableSet = buildSet { + add("modrinth.com") + add("github.com") + add("github.io") + add("githubusercontent.com") // better use github pages + if (isLocalHostAllowed()) { + add("localhost") + } + }.toMutableSet() + + /** + * API FOR MODPACKERS etc all-in-one packs + * @param host host to add. + * @param requester any object. It is recommended that .toString explicitly give out your name. + */ + @Throws(Exception::class) + internal fun addAllowedHosts(host: String?, requester: Any?) { + if (host == null || requester == null) { + Out.securityWarning("Try to add allowed hosts is failed: null host or requester") + throw Exception("Try to add allowed hosts is failed: null host or requester") + } + + Out.securityWarning("==== SECURITY WARNING ====") + Out.securityWarning("# The DynamicPack mod limits the hosts it can interact with.") + Out.securityWarning("# But a certain requester allowed the mod another host to interact with") + Out.securityWarning("# ") + Out.securityWarning("# Host: $host") + Out.securityWarning("# Requester: $requester") + Out.securityWarning("# StackTrace:") + Out.securityStackTrace() + Out.securityWarning("# ") + Out.securityWarning("===========================") + + ALLOWED_HOSTS += host + } + + @Throws(URISyntaxException::class) + fun getUrlHost(url: String): String? = URI(url).host + + @Throws(IOException::class) + fun isUrlHostTrusted(url: String): Boolean { + return try { + val host = getUrlHost(url) ?: return false + when { + host in ALLOWED_HOSTS -> true + ALLOWED_HOSTS.any { host.endsWith(".$it") } -> true + else -> { + Out.warn("Check trusted(false): $host") + false + } + } + } catch (e: Exception) { + throw IOException("Error while check url for trust", e) + } + } + + fun megabyte(mb: Long): Long = 1024L * 1024L * mb + + fun speedToString(bytesPerSec: Long): String = when { + bytesPerSec >= 1024 * 1024 -> "${bytesPerSec / 1024 / 1024} MiB/s" + bytesPerSec >= 1024 -> "${bytesPerSec / 1024} KiB/s" + else -> "$bytesPerSec B/s" + } + + fun secondsToString(s: Long): String = when { + s > 3600 -> "${s / 3600}h" + s > 60 -> "${s / 60}m" + else -> "${s}s" + } + + fun isBlockAllNotTrustedNetworks(): Boolean = true + + // TRUE FOR ALL PUBLIC VERSION!!!!!! + // false is equal not safe!1!!! + fun isRelease(): Boolean = !DEBUG + + // localhost allowed RELEASE=false + fun isLocalHostAllowed(): Boolean = DEBUG_ALLOW_UNSECURE + + // file_debug_only:// allowed RELEASE=false + fun isFileDebugSchemeAllowed(): Boolean = DEBUG_ALLOW_UNSECURE + + // http:// allowed RELEASE=false + fun isHTTPTrafficAllowed(): Boolean = false + + fun debugNetwork(bytesRead: Int, total: Long) { + if (isRelease()) return + if (true) return // Забавная проверка :) оставим семантику как есть. + + try { + Thread.sleep(200) + } catch (e: InterruptedException) { + throw RuntimeException(e) + } + } + + fun isDebugLogs(): Boolean = DEBUG_LOGS + + fun isDebugMessageOnWorldJoin(): Boolean = DEBUG +} \ No newline at end of file diff --git a/src/main/kotlin/com/calculatorsteam/dynamicpack/DynamicPackMod.kt b/src/main/kotlin/com/calculatorsteam/dynamicpack/DynamicPackMod.kt new file mode 100644 index 0000000..48a376b --- /dev/null +++ b/src/main/kotlin/com/calculatorsteam/dynamicpack/DynamicPackMod.kt @@ -0,0 +1,130 @@ +package com.calculatorsteam.dynamicpack + +import com.calculatorsteam.dynamicpack.client.GameStartSyncing +import com.calculatorsteam.dynamicpack.client.config.Config +import com.calculatorsteam.dynamicpack.pack.DynamicResourcePack +import com.calculatorsteam.dynamicpack.pack.Remote +import com.calculatorsteam.dynamicpack.util.enums.Loader +import com.calculatorsteam.dynamicpack.util.log.Out +import org.jetbrains.annotations.ApiStatus +import java.io.File +import java.nio.charset.StandardCharsets +import java.nio.file.Files + +/** + * Base mod entry, singleton instance kept in [instance]. + */ +abstract class DynamicPackMod protected constructor() { + + private lateinit var loader: Loader + private lateinit var gameDir: File // .minecraft + private lateinit var configDir: File // *gamedir*/config/dynamicpack + private lateinit var configFile: File // *configDir*/config.json + private var _config: Config? = null + private lateinit var packsContainer: PacksContainer + private lateinit var gameStartSyncing: GameStartSyncing + private var minecraftInitialized: Boolean = false + + companion object { + private var INSTANCE: DynamicPackMod? = null + + @JvmStatic + val instance: DynamicPackMod + get() = INSTANCE ?: throw IllegalStateException("Mod not initialized") + + @JvmStatic + val config: Config + get() = instance._config ?: error("Config not initialized!") + + @JvmStatic + @ApiStatus.AvailableSince("1.0.30") + @Throws(Exception::class) + fun addAllowedHosts(host: String, requester: Any) { + Constants.addAllowedHosts(host, requester) + } + + @JvmStatic + fun isNameIsDynamic(name: String): Boolean = + instance.packsContainer.getByFileName(name.removePrefix("file/")) != null + + @JvmStatic + fun getDynamicPackByMinecraftName(name: String): DynamicResourcePack? { + return instance.packsContainer.getByFileName(name.removePrefix("file/")) + } + + @JvmStatic + fun isResourcePackActive(pack: DynamicResourcePack): Boolean { + val optionsFile = File(instance.gameDir, "options.txt") + val lines: List = try { + Files.readAllLines(optionsFile.toPath(), StandardCharsets.UTF_8) + } catch (e: Exception) { + Out.println("options.txt not exists or failed to parse.. isResourcePackActive => false.") + return false + } + + return lines.any { line -> + line.startsWith("resourcePacks:") && line.contains(pack.minecraftId) + } + } + + @JvmStatic val gameDir: File get() = instance.gameDir + @JvmStatic val packsContainer: PacksContainer get() = instance.packsContainer + @JvmStatic val loader: Loader get() = instance.loader + @JvmStatic val gameStartSyncing: GameStartSyncing get() = instance.gameStartSyncing + @JvmStatic val configDir: File get() = instance.configDir + @JvmStatic val configFile: File get() = instance.configFile + } + + protected var manuallySyncThreadCounter: Int = 0 + + /** + * Основная инициализация мода. + */ + open fun init(gameDir: File, loader: Loader) { + if (INSTANCE != null) throw RuntimeException("Already initialized!") + INSTANCE = this + this.gameDir = gameDir + this.loader = loader + + // *gamedir*/resourcepacks + val resourcePacks = File(gameDir, "resourcepacks") + resourcePacks.mkdirs() + + this.configDir = File(gameDir, "config/dynamicpack").apply { mkdirs() } + this.configFile = File(configDir, "config.json") + + // Передаём путь внутрь Config перед загрузкой! + Config.fileRef = this.configFile + val loadedConfig = Config.load() + this._config = loadedConfig + + Remote.initRemoteTypes() + Out.init() + Out.println("Mod version: ${Constants.VERSION_NAME} build: ${Constants.VERSION_BUILD}") + + this.packsContainer = PacksContainer(resourcePacks) + this.packsContainer.rescan() + this.gameStartSyncing = GameStartSyncing() + + if (loadedConfig.isAutoUpdateAtLaunch()) { + this.gameStartSyncing.start() + } + } + + // == ABSTRACT API == + abstract fun isModExists(id: String): Boolean + /** Manually re-sync all supported packs */ + abstract fun startManuallySync() + abstract fun startManuallySync(pack: DynamicResourcePack) + abstract fun needResourcesReload() + abstract fun getCurrentGameVersion(): String + @Throws(Exception::class) + abstract fun checkResourcePackMetaValid(s: String): Boolean + // == END ABSTRACT == + + fun minecraftInitialized() { + this.minecraftInitialized = true + } + + fun isMinecraftInitialized(): Boolean = minecraftInitialized +} \ No newline at end of file diff --git a/src/main/kotlin/com/calculatorsteam/dynamicpack/InputValidator.kt b/src/main/kotlin/com/calculatorsteam/dynamicpack/InputValidator.kt new file mode 100644 index 0000000..b4f1ca0 --- /dev/null +++ b/src/main/kotlin/com/calculatorsteam/dynamicpack/InputValidator.kt @@ -0,0 +1,109 @@ +package com.calculatorsteam.dynamicpack + +import com.calculatorsteam.dynamicpack.util.log.Out +import java.net.URISyntaxException +import java.nio.charset.StandardCharsets +import java.util.regex.Pattern + +/** + * Validates for [user/resourcepack-creator] input values + */ +object InputValidator { + private val CONTENT_ID_PATTERN: Pattern = Pattern.compile("^[a-z0-9_:-]{2,128}$") + private val PATH_PATTERN: Pattern = Pattern.compile("^[A-Za-z0-9_./() +-]{0,255}$") + private val URL_PATTERN: Pattern = Pattern.compile( + "(https?://)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)" + ) + + /** + * dynamic content id valid? + */ + @JvmStatic + fun isDynamicContentIdValid(contentId: String?): Boolean = + contentId != null && CONTENT_ID_PATTERN.matcher(contentId).matches() + + /** + * Throw if content id invalid + */ + @JvmStatic + fun throwIsContentIdInvalid(contentId: String?) { + if (!isDynamicContentIdValid(contentId)) { + throw RuntimeException("Id of content is not valid: ${safeOutput(contentId ?: "")}") + } + } + + /** + * Is dynamic_repo content name valid? + */ + @JvmStatic + fun isDynamicContentNameValid(contentName: String?): Boolean = + contentName?.trim()?.let { + it.length < 64 && it.isNotEmpty() && + !it.contains("\n") && !it.contains("\r") && !it.contains("\b") + } ?: false + + /** + * Dynamic pack name valid? + */ + @JvmStatic + fun isDynamicPackNameValid(name: String?): Boolean = + name?.trim()?.let { + it.length < 64 && it.isNotEmpty() && + !it.contains("\n") && !it.contains("\r") && !it.contains("\b") + } ?: false + + /** + * Throw if local path invalid + */ + @JvmStatic + fun throwIsPathInvalid(path: String?) { + if (path == null) { + throw SecurityException("Null path", NullPointerException("path to valid is null")) + } + + val trim = path.trim() + if (trim.length < 2 || !PATH_PATTERN.matcher(path).matches()) { + val safe = path.toByteArray(StandardCharsets.US_ASCII).toString(StandardCharsets.US_ASCII) + throw SecurityException("Not valid path: $safe") + } + } + + /** + * Is URL valid? + */ + @JvmStatic + fun isUrlValid(url: String): Boolean { + try { + if (Constants.isLocalHostAllowed() && Constants.getUrlHost(url) == "localhost") { + Out.warn("isUrlValid return true for localhost! Behavior only when isLocalHostAllowed()=true") + return true + } + } catch (_: URISyntaxException) { } + return URL_PATTERN.matcher(url).matches() + } + + /** + * Throw if url invalid + */ + @JvmStatic + fun throwIsUrlInvalid(url: String?) { + if (url == null) { + throw SecurityException("null", NullPointerException("url to valid is null")) + } + if (!isUrlValid(url)) { + throw SecurityException("Not valid url: ${safeOutput(url)}") + } + } + + /** + * SHA1 valid? + */ + @JvmStatic + fun isHashValid(hash: String?): Boolean = + hash != null && hash.length == 40 && !hash.contains(" ") + + private fun safeOutput(s: String): String { + val short = if (s.length >= 100) s.take(100) else s + return short.toByteArray(StandardCharsets.US_ASCII).toString(StandardCharsets.US_ASCII) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/calculatorsteam/dynamicpack/PacksContainer.kt b/src/main/kotlin/com/calculatorsteam/dynamicpack/PacksContainer.kt new file mode 100644 index 0000000..4930b94 --- /dev/null +++ b/src/main/kotlin/com/calculatorsteam/dynamicpack/PacksContainer.kt @@ -0,0 +1,103 @@ +package com.calculatorsteam.dynamicpack + +import com.calculatorsteam.dynamicpack.pack.DynamicResourcePack +import com.calculatorsteam.dynamicpack.util.JsonUtil +import com.calculatorsteam.dynamicpack.util.JsonUtil.optInt +import com.calculatorsteam.dynamicpack.util.PackUtil +import com.calculatorsteam.dynamicpack.util.PathUtil +import com.calculatorsteam.dynamicpack.util.log.Out +import com.calculatorsteam.dynamicpack.util.exception.FailedOpenPackFileSystemException +import java.io.File +import java.nio.file.Files +import java.nio.file.Path + +/** + * Container for supported packs + */ +class PacksContainer(private val directoryToCheck: File) { + + private var rescanPacksBlocked: Boolean = false + private var isPacksScanning: Boolean = false + + /** Current dynamic packs by filename */ + private val packs: MutableMap = mutableMapOf() + + fun lockRescan() { + rescanPacksBlocked = true + } + + fun unlockRescan() { + rescanPacksBlocked = false + } + + fun rescan() { + if (isPacksScanning) { + Out.warn("Already in scanning!") + return + } + if (rescanPacksBlocked) { + Out.warn("Rescan blocked! maybe currently syncing") + return + } + + isPacksScanning = true + val forDelete = packs.keys.toMutableList() + + PathUtil.listFiles(directoryToCheck)?.forEach { packFile -> + val currentDynamicPack = DynamicPackMod.getDynamicPackByMinecraftName("file/${packFile.name}") + if (currentDynamicPack?.isSyncing == true) { + Out.warn("WARNING: Found a pack that is now synchronizing. skipping this pack") + return@forEach + } + + try { + PackUtil.openPackFileSystem(packFile) { packPath -> + val clientFile = packPath.resolve(Constants.CLIENT_FILE) + if (Files.exists(clientFile)) { + Out.println("+ Pack ${packFile.name} supported by mod!") + processPack(packFile, clientFile) + forDelete.remove(packFile.name) + } else { + Out.println("- Pack ${packFile.name} not supported by mod.") + } + } + } catch (e: Exception) { + if (e is FailedOpenPackFileSystemException) { + Out.warn("Error while processing pack ${packFile.name}: ${e.message}") + } else { + Out.error("Error while processing pack: ${packFile.name}", e) + } + } + } + + forDelete.forEach { s -> + Out.println("Pack $s no longer exist or no longer support DynamicPack!") + packs.remove(s) + } + + isPacksScanning = false + } + + @Throws(Exception::class) + private fun processPack(location: File, clientFile: Path) { + val json = JsonUtil.readJson(clientFile) + val formatVersion = json.optInt("formatVersion") + val oldestPack = packs[location.name] + + if (formatVersion == 1) { + val pack = DynamicResourcePack(location, json).apply { + if (oldestPack != null) { + flashback(oldestPack) + } + } + packs[location.name] = pack + } else { + throw RuntimeException("Unsupported formatVersion for pack ${location.name}: $formatVersion") + } + } + + val packsArray: Array + get() = packs.values.toTypedArray() + + fun getByFileName(filename: String): DynamicResourcePack? = packs[filename] +} \ No newline at end of file diff --git a/src/main/kotlin/com/calculatorsteam/dynamicpack/client/DynamicPackModBase.kt b/src/main/kotlin/com/calculatorsteam/dynamicpack/client/DynamicPackModBase.kt new file mode 100644 index 0000000..ff323af --- /dev/null +++ b/src/main/kotlin/com/calculatorsteam/dynamicpack/client/DynamicPackModBase.kt @@ -0,0 +1,152 @@ +package com.calculatorsteam.dynamicpack.client + +import com.calculatorsteam.dynamicpack.DynamicPackMod +import com.calculatorsteam.dynamicpack.Constants +import com.calculatorsteam.dynamicpack.pack.DynamicResourcePack +import com.calculatorsteam.dynamicpack.platform.VersionFunctions +import com.calculatorsteam.dynamicpack.util.status.StatusChecker +import com.calculatorsteam.dynamicpack.sync.SyncThread +import com.calculatorsteam.dynamicpack.util.log.Out +import com.google.gson.JsonElement +import com.google.gson.JsonObject +import com.google.gson.internal.LazilyParsedNumber +import net.minecraft.ChatFormatting +import net.minecraft.SharedConstants +import net.minecraft.client.Minecraft +import net.minecraft.client.gui.components.toasts.SystemToast +import net.minecraft.client.player.LocalPlayer +import net.minecraft.network.chat.Component +import net.minecraft.network.chat.Style +import net.minecraft.util.GsonHelper +import java.net.URI + +/** + * Base impl for DynamicPack mod (minecraft logic) + *
+ * == inheritance tree ==
+ * DynamicPackMod - mod-related logic
+ * | DynamicPackModBase - minecraft-related logic
+ * . | fabric impl...
+ * . | forge impl...
+ * . | ...
+ * 
+ */ +abstract class DynamicPackModBase : DynamicPackMod() { + + private var toast: SystemToast? = null + private var toastUpdated: Long = 0 + + fun setToastContent(title: Component, text: Component) { + if (!isMinecraftInitialized()) return + + val now = System.currentTimeMillis() + if (toast == null || (now - toastUpdated > 5000)) { + val toastManager = VersionFunctions.getToastManager() + toast = SystemToast( + VersionFunctions.getSystemToastId(), + title, + text + ).also { toastManager.addToast(it) } + } else { + toast?.reset(title, text) + } + toastUpdated = now + } + + private fun createDownloadComponent(): Component = + Component.translatable("dynamicpack.status_checker.download") + .withStyle( + Style.EMPTY + .withHoverEvent( + VersionFunctions.getHoverEventShowText( + Component.translatable( + "dynamicpack.status_checker.download.hover", + Component.literal(Constants.MODRINTH_URL) + .withStyle(ChatFormatting.UNDERLINE, ChatFormatting.AQUA) + ) + ) + ) + .withClickEvent( + VersionFunctions.getClickEventOpenUrl(Constants.MODRINTH_URL) + ) + ) + .withStyle(ChatFormatting.YELLOW, ChatFormatting.UNDERLINE) + + fun onWorldJoinForUpdateChecks(player: LocalPlayer?) { + if (Constants.isDebugMessageOnWorldJoin()) { + VersionFunctions.displayClientMessage( + player, + Component.literal("Debug message on world join") + .withStyle(ChatFormatting.GREEN) + ) + } + when { + player == null -> Out.warn("player == null on world join") + !StatusChecker.isSafe() -> { + VersionFunctions.displayClientMessage( + player, + Component.translatable( + "dynamicpack.status_checker.not_safe", + createDownloadComponent() + ) + ) + setToastContent( + Component.translatable("dynamicpack.status_checker.not_safe.toast.title"), + Component.translatable("dynamicpack.status_checker.not_safe.toast.description") + ) + } + !StatusChecker.isFormatActual() -> VersionFunctions.displayClientMessage( + player, + Component.translatable( + "dynamicpack.status_checker.format_not_actual", + createDownloadComponent() + ) + ) + + StatusChecker.isModUpdateAvailable() -> + Out.println("DynamicPack mod update available: ${Constants.MODRINTH_URL}") + + !StatusChecker.isChecked() -> + Out.warn("StatusChecker isChecked = false :(") + + else -> Out.println("Mod in actual state in current time!") + } + } + + override fun startManuallySync() { + SyncThread("SyncThread-${manuallySyncThreadCounter++}").start() + } + + override fun startManuallySync(pack: DynamicResourcePack) { + SyncThread("SyncThread-${manuallySyncThreadCounter++}", pack).start() + } + + override fun getCurrentGameVersion(): String { + SharedConstants.tryDetectVersion() + return VersionFunctions.versionName(SharedConstants.getCurrentVersion()) + } + + override fun checkResourcePackMetaValid(s: String): Boolean { + val pack: JsonObject = GsonHelper.parse(s).getAsJsonObject("pack") + if (pack["pack_format"].asNumber is LazilyParsedNumber) { + (pack["pack_format"].asNumber as LazilyParsedNumber).toInt() + } + val description: JsonElement = pack["description"] + if (description.isJsonNull) { + throw NullPointerException("description is null in pack.mcmeta") + } + return true + } + + override fun needResourcesReload() { + val client = Minecraft.getInstance() + if (client != null && client.level == null) { + client.execute { client.reloadResourcePacks() } + } else { + setToastContent( + Component.translatable("dynamicpack.toast.needReload"), + Component.translatable("dynamicpack.toast.needReload.description") + ) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/calculatorsteam/dynamicpack/client/GameStartSyncing.kt b/src/main/kotlin/com/calculatorsteam/dynamicpack/client/GameStartSyncing.kt new file mode 100644 index 0000000..ad30ae8 --- /dev/null +++ b/src/main/kotlin/com/calculatorsteam/dynamicpack/client/GameStartSyncing.kt @@ -0,0 +1,150 @@ +package com.calculatorsteam.dynamicpack.client + +import com.calculatorsteam.dynamicpack.client.config.Config +import com.calculatorsteam.dynamicpack.DynamicPackMod +import com.calculatorsteam.dynamicpack.util.status.StatusChecker +import com.calculatorsteam.dynamicpack.sync.SyncBuilder +import com.calculatorsteam.dynamicpack.sync.SyncProgress +import com.calculatorsteam.dynamicpack.sync.SyncingTask +import com.calculatorsteam.dynamicpack.util.log.LoopLog +import com.calculatorsteam.dynamicpack.util.log.NetworkStat +import com.calculatorsteam.dynamicpack.util.log.Out +import java.nio.file.Path +import kotlin.time.Duration.Companion.seconds + +/** + * Syncing on game launch + */ +class GameStartSyncing : Thread("GameStartSyncingThread") { + + companion object { + private const val MAX_LOCK_MS = 1000 * 15 + } + + private var updateStartTime: Long = 0L // thread started time ms + private var lockStartTime: Long = 0L // lock started time ms + + /** locking resources loading (firstly true!) */ + var lockResourcesLoading: Boolean = true + private set + + var syncBuilder: SyncBuilder? = null + val etaLoopLog = LoopLog(1.seconds) + + init { + if (!Config.getInstance().isAutoUpdateAtLaunch()) { + Out.warn("Auto-update at launch disabled by config.") + unlock() + } + } + + /** + * Starting syncing... (thread entrypoint) + */ + override fun run() { + if (!Config.getInstance().isAutoUpdateAtLaunch()) { + Out.warn("Thread launched with isAutoUpdateAtLaunch=false; return") + return + } + + updateStartTime = System.currentTimeMillis() + Out.debug("[GameStartSyncing] thread started") + + SyncingTask.launchTaskAsSyncing { + try { + StatusChecker.check() // check status + SyncingTask.currentRootSyncBuilder = SyncingTask.rootSyncBuilder().also { builder -> + syncBuilder = builder + builder.init(ignoreCaches = false) + + if (builder.isUpdateAvailable) { + val reloadRequired = builder.doUpdate(createSyncProgress()) + if (!lockResourcesLoading && reloadRequired) { + DynamicPackMod.instance.needResourcesReload() + } + } + } + } catch (e: Exception) { + Out.error("Error while GameStartSyncing...", e) + } finally { + unlock() // unlock main thread! + SyncingTask.currentRootSyncBuilder = null + } + } + } + + private fun createSyncProgress(): SyncProgress = object : SyncProgress { + override fun setPhase(phase: String) { + Out.debug("Phase: $phase") + SyncingTask.log(phase) + } + + override fun downloading(name: String, percentage: Float) { + syncBuilder?.let { builder -> + val remainsBytes = builder.updateSize - builder.downloadedSize + val eta = NetworkStat.remainingETA(remainsBytes).also { SyncingTask.eta = it } + + if (etaLoopLog.tick()) { + Out.debug("(${SyncingTask.currentPackName}) ETA=${eta}s") + } + + // if locked and updating > 3 seconds + if (updateTime > 3000 && isLocked()) { + val shouldUnlock = eta * 1000 > (untilForceUnlock / 1.5f) + if (shouldUnlock) { + Out.debug("[GameStartSyncing] ETA ${eta}s. Unlocking main thread...") + unlock() + } + } + } + } + + override fun deleted(name: Path) { + Out.debug("Deleted: $name") + SyncingTask.log("Delete: ${name.fileName}") + } + } + + // если конфликт модов → переопределить + fun isLockSupported(): Boolean = true + + fun lockedTick(): Boolean { + if (lockTime > MAX_LOCK_MS) { + Out.warn("Main thread unlocked forcibly because lock time >= 15s") + return false + } + return true + } + + val lockTime: Long + get() = System.currentTimeMillis() - lockStartTime + + val updateTime: Long + get() = System.currentTimeMillis() - updateStartTime + + val untilForceUnlock: Long + get() = MAX_LOCK_MS - lockTime + + fun endGameLocking() { + Out.println("Main thread locked for ${lockTime / 1000} seconds") + } + + fun startGameLocking() { + Out.println("Main thread locked by DynamicPack for updating resource packs...") + lockStartTime = System.currentTimeMillis() + } + + fun isLockStarted(): Boolean = lockStartTime != 0L + fun isLocked(): Boolean = isLockStarted() && lockResourcesLoading + + private fun unlock() { + lockResourcesLoading = false + } + + val percentage: Double + get() = syncBuilder?.let { b -> + if (b.downloadedSize > 0) + (b.downloadedSize.toDouble() / b.updateSize.toDouble()) * 100.0 + else 0.0 + } ?: 0.0 +} \ No newline at end of file diff --git a/src/main/kotlin/com/calculatorsteam/dynamicpack/client/PackMixinHelper.kt b/src/main/kotlin/com/calculatorsteam/dynamicpack/client/PackMixinHelper.kt new file mode 100644 index 0000000..b980982 --- /dev/null +++ b/src/main/kotlin/com/calculatorsteam/dynamicpack/client/PackMixinHelper.kt @@ -0,0 +1,19 @@ +package com.calculatorsteam.dynamicpack.client + +import com.calculatorsteam.dynamicpack.DynamicPackMod + +/** + * Helper for mixin hooks into Minecraft lifecycle. + */ +object PackMixinHelper { + + @JvmStatic + fun minecraftInitReturned() { + DynamicPackMod.instance.minecraftInitialized() + } + + @JvmStatic + fun updatePacksMinecraftRequest() { + DynamicPackMod.packsContainer.rescan() + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/calculatorsteam/dynamicpack/client/config/Config.kt b/src/main/kotlin/com/calculatorsteam/dynamicpack/client/config/Config.kt new file mode 100644 index 0000000..8259005 --- /dev/null +++ b/src/main/kotlin/com/calculatorsteam/dynamicpack/client/config/Config.kt @@ -0,0 +1,151 @@ +package com.calculatorsteam.dynamicpack.client.config + +import com.calculatorsteam.dynamicpack.Constants +import com.calculatorsteam.dynamicpack.pack.dynamicrepo.DynamicRepoSyncBuilder +import com.calculatorsteam.dynamicpack.util.PathUtil +import com.calculatorsteam.dynamicpack.util.log.FileLog +import com.calculatorsteam.dynamicpack.util.log.Out +import java.io.File +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardOpenOption + +/** + * Global config for DynamicPack. + */ +class Config private constructor() { + + @Transient + private var def: Boolean = false + + private var formatVersion: Int = 1 // do not touch + + private var networkBufferSize: Int = 1024 + fun getNetworkBufferSize(): Int = networkBufferSize + fun setNetworkBufferSize(value: Int) { + networkBufferSize = value + updateStaticVariables(this) + } + + private var networkMultithreadDownloadThreads: Int = 12 + fun getNetworkMultithreadDownloadThreads(): Int = networkMultithreadDownloadThreads + fun setNetworkMultithreadDownloadThreads(value: Int) { + networkMultithreadDownloadThreads = value + updateStaticVariables(this) + } + + private var logAllFilesChanges: Boolean = false + fun isLogAllFilesChanges(): Boolean = logAllFilesChanges + fun setLogAllFilesChanges(value: Boolean) { + logAllFilesChanges = value + updateStaticVariables(this) + } + + private var autoUpdateAtLaunch: Boolean = true + fun isAutoUpdateAtLaunch(): Boolean = autoUpdateAtLaunch + fun setAutoUpdateAtLaunch(value: Boolean) { + autoUpdateAtLaunch = value + } + + private var updateOnlyEnabledPacks: Boolean = true + fun isUpdateOnlyEnabledPacks(): Boolean = updateOnlyEnabledPacks + fun setUpdateOnlyEnabledPacks(value: Boolean) { + updateOnlyEnabledPacks = value + } + + private var debugIgnoreHiddenFlagInContents: Boolean = false + fun dynamicRepoIsIgnoreHiddenContentFlag(): Boolean = debugIgnoreHiddenFlagInContents + fun setDebugIgnoreHiddenFlagInContents(value: Boolean) { + debugIgnoreHiddenFlagInContents = value + } + + private var debugLogs: Boolean = false + fun isDebugLogs(): Boolean = debugLogs + fun setDebugLogs(value: Boolean) { + debugLogs = value + } + + private fun checkAndValidateConfig() { + var save = false + + if (networkBufferSize < 256) { + networkBufferSize = 256 + save = true + Out.warn("Config invalid 'networkBufferSize'. Sets to $networkBufferSize") + } + + if (networkMultithreadDownloadThreads !in 1..<256) { + networkMultithreadDownloadThreads = 8 + save = true + Out.warn("Config invalid 'networkMultithreadDownloadThreads'. Sets to $networkMultithreadDownloadThreads") + } + + if (save) save() + } + + fun save() { + if (def) throw RuntimeException("Can't save a DEF config!") + try { + val json = Constants.GSON.toJson(this) + val file: Path = fileRef!!.toPath() + PathUtil.delete(file) + PathUtil.createDirsToFile(file) + PathUtil.createFile(file) + Files.writeString(file, json, StandardOpenOption.WRITE) + } catch (e: Exception) { + Out.error("Config save failed :(", e) + } + } + + companion object { + @JvmField val DEF: Config = createDefConfig() + private var instance: Config? = null + internal var fileRef: File? = null + + private fun createDefConfig(): Config { + val cfg = Config() + cfg.def = true + return cfg + } + + @JvmStatic + fun load(): Config { + if (instance != null) throw RuntimeException("Config already loaded") + + val file = fileRef ?: throw RuntimeException("Config.fileRef not set before load()!") + + if (!file.exists()) { + val cfg = Config() + updateStaticVariables(cfg) + instance = cfg + return cfg + } + + return try { + val config = Constants.GSON.fromJson( + PathUtil.readString(file.toPath()), Config::class.java + ) + updateStaticVariables(config) + instance = config + config + } catch (e: Exception) { + Out.error("Config load failed (return default config)", e) + val fallback = Config() + updateStaticVariables(fallback) + instance = fallback + fallback + } + } + + private fun updateStaticVariables(config: Config) { + config.checkAndValidateConfig() + Constants.URLS_BUFFER_SIZE = config.networkBufferSize + Constants.DEBUG_LOGS = config.debugLogs + DynamicRepoSyncBuilder.DOWNLOAD_THREADS_COUNT = config.networkMultithreadDownloadThreads + FileLog.logAllChanges = config.logAllFilesChanges + } + + @JvmStatic + fun getInstance(): Config = instance ?: throw IllegalStateException("Config not initialized!") + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/calculatorsteam/dynamicpack/client/config/ConfigScreenBuilder.kt b/src/main/kotlin/com/calculatorsteam/dynamicpack/client/config/ConfigScreenBuilder.kt new file mode 100644 index 0000000..ab8dfaa --- /dev/null +++ b/src/main/kotlin/com/calculatorsteam/dynamicpack/client/config/ConfigScreenBuilder.kt @@ -0,0 +1,168 @@ +package com.calculatorsteam.dynamicpack.client.config + +import com.calculatorsteam.dynamicpack.DynamicPackMod +import com.calculatorsteam.dynamicpack.sync.SyncingTask +import dev.isxander.yacl3.api.* +import dev.isxander.yacl3.api.controller.BooleanControllerBuilder +import dev.isxander.yacl3.api.controller.IntegerSliderControllerBuilder +import dev.isxander.yacl3.api.controller.TickBoxControllerBuilder +import dev.isxander.yacl3.gui.YACLScreen +import dev.isxander.yacl3.gui.controllers.slider.IntegerSliderController +import net.minecraft.ChatFormatting +import net.minecraft.client.gui.screens.Screen +import net.minecraft.network.chat.Component + +object ConfigScreenBuilder { + @JvmStatic + fun create(parent: Screen): Screen { + val config = YetAnotherConfigLib.createBuilder() + .title(Component.literal("DynamicPack")) + .category(buildGeneralCategory()) + .category(buildNetworkCategory()) + .category(buildDebugCategory()) + .save { DynamicPackMod.config.save() } + .build() + + return YACLScreen(config, parent) + } + + private fun buildGeneralCategory(): ConfigCategory = + ConfigCategory.createBuilder() + .name(Component.translatable("dynamicpack.screen.config.category.general")) + .group( + OptionGroup.createBuilder() + .option( + Option.createBuilder() + .name(Component.translatable("dynamicpack.screen.config.category.general.isAutoUpdateAtLaunch")) + .binding( + Config.DEF.isAutoUpdateAtLaunch(), + { DynamicPackMod.config.isAutoUpdateAtLaunch() }, + { DynamicPackMod.config.setAutoUpdateAtLaunch(it) } + ) + .controller { BooleanControllerBuilder.create(it).yesNoFormatter() } + .build() + ) + .option( + Option.createBuilder() + .name(Component.translatable("dynamicpack.screen.config.category.general.updateOnlyEnabledPacks")) + .binding( + Config.DEF.isUpdateOnlyEnabledPacks(), + { DynamicPackMod.config.isUpdateOnlyEnabledPacks() }, + { DynamicPackMod.config.setUpdateOnlyEnabledPacks(it) } + ) + .controller { BooleanControllerBuilder.create(it).yesNoFormatter() } + .build() + ) + .build() + ) + .build() + + private fun buildDebugCategory(): ConfigCategory = + ConfigCategory.createBuilder() + .name(Component.translatable("dynamicpack.screen.config.category.debug")) + .tooltip(Component.translatable("dynamicpack.screen.config.category.debug.description").withStyle(ChatFormatting.RED)) + .group( + OptionGroup.createBuilder() + .name(Component.literal("Calculator's category ^_^")) + .option( + Option.createBuilder() + .name(Component.translatable("dynamicpack.screen.config.category.debug.logAllFilesChanges")) + .binding( + Config.DEF.isLogAllFilesChanges(), + { DynamicPackMod.config.isLogAllFilesChanges() }, + { DynamicPackMod.config.setLogAllFilesChanges(it) } + ) + .controller(TickBoxControllerBuilder::create) + .build() + ) + .option( + Option.createBuilder() + .name(Component.translatable("dynamicpack.screen.config.category.debug.ignoreHidden")) + .binding( + Config.DEF.dynamicRepoIsIgnoreHiddenContentFlag(), + { DynamicPackMod.config.dynamicRepoIsIgnoreHiddenContentFlag() }, + { DynamicPackMod.config.setDebugIgnoreHiddenFlagInContents(it) } + ) + .controller(TickBoxControllerBuilder::create) + .build() + ) + .option( + Option.createBuilder() + .name(Component.literal("INTERRUPT UPDATING")) + .description(OptionDescription.of(Component.literal("EXPERIMENTAL FUNCTIONAL"))) + .binding(object : Binding { + override fun setValue(value: Boolean) { + SyncingTask.currentRootSyncBuilder?.interrupt() + } + override fun getValue(): Boolean = false + override fun defaultValue(): Boolean = false + }) + .controller(TickBoxControllerBuilder::create) + .build() + ) + .build() + ) + .build() + + private fun buildNetworkCategory(): ConfigCategory = + ConfigCategory.createBuilder() + .name(Component.translatable("dynamicpack.screen.config.category.network")) + .tooltip(Component.translatable("dynamicpack.screen.config.category.network.tooltip")) + .group( + OptionGroup.createBuilder() + .name(Component.translatable("dynamicpack.screen.config.category.network.group.name")) + .description(OptionDescription.of(Component.translatable("dynamicpack.screen.config.category.network.group.description"))) + .option( + Option.createBuilder() + .name(Component.translatable("dynamicpack.screen.config.category.network.bufferSize.name")) + .binding( + Config.DEF.getNetworkBufferSize(), + { DynamicPackMod.config.getNetworkBufferSize() }, + { DynamicPackMod.config.setNetworkBufferSize(it) } + ) + .controller { + IntegerSliderControllerBuilder.create(it) + .step(256) + .range(256, 8192) + } + .build() + ) + .option( + Option.createBuilder() + .name(Component.translatable("dynamicpack.screen.config.category.network.multithread.threads.name")) + .binding( + Config.DEF.getNetworkMultithreadDownloadThreads(), + { DynamicPackMod.config.getNetworkMultithreadDownloadThreads() }, + { DynamicPackMod.config.setNetworkMultithreadDownloadThreads(it) } + ) + .controller { integerOption -> + IntegerSliderControllerBuilder.create(integerOption) + .step(1) + .formatValue { value -> + when { + value >= 255 -> Component.literal("^_^ ") + .withStyle(ChatFormatting.STRIKETHROUGH, ChatFormatting.GOLD) + .append(Component.literal(value.toString()).withStyle(ChatFormatting.RESET, ChatFormatting.BOLD, ChatFormatting.GOLD)) + value > 80 -> Component.literal("X_X ") + .withStyle(ChatFormatting.DARK_RED) + .append(Component.literal(value.toString()).withStyle(ChatFormatting.BOLD, ChatFormatting.DARK_RED)) + value > 64 -> Component.literal("X_0 ") + .withStyle(ChatFormatting.DARK_RED) + .append(Component.literal(value.toString()).withStyle(ChatFormatting.BOLD)) + value > 32 -> Component.literal("0_0 ") + .withStyle(ChatFormatting.RED) + .append(Component.literal(value.toString()).withStyle(ChatFormatting.BOLD)) + value > 16 -> Component.literal("OwO ") + .withStyle(ChatFormatting.YELLOW) + .append(Component.literal(value.toString()).withStyle(ChatFormatting.BOLD)) + else -> IntegerSliderController.DEFAULT_FORMATTER.apply(value) + } + } + .range(1, 255) + } + .build() + ) + .build() + ) + .build() +} \ No newline at end of file diff --git a/src/main/kotlin/com/calculatorsteam/dynamicpack/client/config/NoYACLScreen.kt b/src/main/kotlin/com/calculatorsteam/dynamicpack/client/config/NoYACLScreen.kt new file mode 100644 index 0000000..fd21425 --- /dev/null +++ b/src/main/kotlin/com/calculatorsteam/dynamicpack/client/config/NoYACLScreen.kt @@ -0,0 +1,108 @@ +package com.calculatorsteam.dynamicpack.client.config; + +import com.calculatorsteam.dynamicpack.platform.VersionFunctions +import net.minecraft.ChatFormatting +import net.minecraft.Util +import net.minecraft.client.gui.GuiGraphics +import net.minecraft.client.gui.components.Button +import net.minecraft.client.gui.screens.Screen +import net.minecraft.network.chat.ClickEvent +import net.minecraft.network.chat.CommonComponents +import net.minecraft.network.chat.Component +import net.minecraft.network.chat.Style +import net.minecraft.util.FormattedCharSequence +import net.minecraft.util.Mth +import java.net.URI + +/** + * Screen displayed if YACL (YetAnotherConfigLib) is not found. + */ +open class NoYACLScreen(private val parent: Screen) : Screen(Component.translatable("dynamicpack.screen.config.no_yacl.title")) { + + private val titleSequence: FormattedCharSequence = + Component.translatable("dynamicpack.screen.config.no_yacl.title") + .withStyle(ChatFormatting.BOLD) + .visualOrderText + + private val unwrappedText: Component = + Component.translatable( + "dynamicpack.screen.config.no_yacl.description", + Component.literal("YetAnotherConfigLib").withStyle { + it.withClickEvent(VersionFunctions.getClickEventOpenUrl("https://modrinth.com/mod/yacl")) + .applyFormats(ChatFormatting.BLUE, ChatFormatting.UNDERLINE) + }, + ) + + private lateinit var wrappedText: List + + override fun init() { + wrappedText = font.split(unwrappedText, width - 50) + + addRenderableWidget( + VersionFunctions.createButton