diff --git a/.github/workflows/build_1605.yml b/.github/workflows/build_1605.yml index 8e181252c..113f4e0a7 100644 --- a/.github/workflows/build_1605.yml +++ b/.github/workflows/build_1605.yml @@ -28,11 +28,11 @@ jobs: with: fetch-depth: 30 - - name: Set up JDK 17 + - name: Set up JDK 21 uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: '17' + java-version: '21' cache: gradle - name: Grant execute permission for gradlew diff --git a/build.gradle b/build.gradle index d33df7551..700434c76 100644 --- a/build.gradle +++ b/build.gradle @@ -1,10 +1,11 @@ plugins { id "architectury-plugin" version "3.4-SNAPSHOT" id "dev.architectury.loom" version "1.7-SNAPSHOT" apply false + id('xyz.wagyourtail.jvmdowngrader').version("${jvmdowngrader_version}").apply(false) } architectury { - minecraft = rootProject.minecraft_version + minecraft = minecraft_version } subprojects { @@ -14,14 +15,21 @@ subprojects { silentMojangMappingsLicense() } + repositories { + maven { + name = 'ParchmentMC' + url = 'https://maven.parchmentmc.org' + } + } + dependencies { - minecraft "com.mojang:minecraft:${rootProject.minecraft_version}" - mappings loom.officialMojangMappings() - //jabel, for modern Java syntax - //https://central.sonatype.com/artifact/com.pkware.jabel/jabel-javac-plugin - annotationProcessor 'com.pkware.jabel:jabel-javac-plugin:1.0.1-1' - compileOnly 'com.pkware.jabel:jabel-javac-plugin:1.0.1-1' - //lambok: https://projectlombok.org/setup/gradle + minecraft("com.mojang:minecraft:${rootProject.minecraft_version}") + mappings(loom.layered { + officialMojangMappings() + parchment("org.parchmentmc.data:parchment-${rootProject.parchment_version}@zip") + }) + + //lombok: https://projectlombok.org/setup/gradle compileOnly 'org.projectlombok:lombok:1.18.34' annotationProcessor 'org.projectlombok:lombok:1.18.34' } @@ -31,6 +39,7 @@ allprojects { apply plugin: "java" apply plugin: "architectury-plugin" apply plugin: "maven-publish" + apply plugin: 'xyz.wagyourtail.jvmdowngrader' //not accessible from time to time // apply from: "https://files.latmod.com/public/markdown-git-changelog.gradle" @@ -40,14 +49,14 @@ allprojects { group = project.maven_group archivesBaseName = project.archives_base_name - tasks.withType(JavaCompile) { + tasks.withType(JavaCompile).configureEach { options.encoding = "UTF-8" sourceCompatibility = 21 // The Minecraft launcher currently installs Java 8 for users, so your mod probably wants to target Java 8 too // JDK 9 introduced a new way of specifying this that will make sure no newer classes or methods are used. // We'll use that if it's available, but otherwise we'll use the older option. - options.release = 8 +// options.release = 8 } repositories { diff --git a/common/src/main/java/dev/latvian/kubejs/BuiltinKubeJSPlugin.java b/common/src/main/java/dev/latvian/kubejs/BuiltinKubeJSPlugin.java index f406e0b0f..e9ab35f9f 100644 --- a/common/src/main/java/dev/latvian/kubejs/BuiltinKubeJSPlugin.java +++ b/common/src/main/java/dev/latvian/kubejs/BuiltinKubeJSPlugin.java @@ -11,7 +11,7 @@ import dev.latvian.kubejs.block.*; import dev.latvian.kubejs.block.custom.*; import dev.latvian.kubejs.block.custom.builder.*; -import dev.latvian.kubejs.block.predicate.BlockStatePredicate; +import dev.latvian.kubejs.block.BlockStatePredicate; import dev.latvian.kubejs.client.painter.Painter; import dev.latvian.kubejs.client.painter.screen.*; import dev.latvian.kubejs.entity.EntityJS; @@ -566,12 +566,12 @@ public void generateAssetJsons(AssetJsonGenerator generator) { } @Override - public void generateLang(Map lang) { - lang.put("itemGroup.kubejs.kubejs", "KubeJS"); + public void generateLang(Map enusLang) { + enusLang.put("itemGroup.kubejs.kubejs", KubeJS.MOD_NAME); for (val builder : RegistryInfos.ALL_BUILDERS) { if (builder.overrideLangJson && builder.display != null) { - lang.put(builder.getTranslationKey(), builder.display.getString()); + enusLang.put(builder.getTranslationKey(), builder.display.getString()); } } } diff --git a/common/src/main/java/dev/latvian/kubejs/CommonProperties.java b/common/src/main/java/dev/latvian/kubejs/CommonProperties.java index dbd3a4791..606f73354 100644 --- a/common/src/main/java/dev/latvian/kubejs/CommonProperties.java +++ b/common/src/main/java/dev/latvian/kubejs/CommonProperties.java @@ -1,91 +1,118 @@ package dev.latvian.kubejs; -import java.io.Reader; -import java.io.Writer; +import dev.latvian.kubejs.util.KubeJSPlugins; +import lombok.val; + import java.nio.file.Files; -import java.nio.file.Path; import java.util.Properties; /** * @author LatvianModder */ public class CommonProperties { - private static CommonProperties instance; - - public static CommonProperties get() { - if (instance == null) { - instance = new CommonProperties(); - } - - return instance; - } - - private final Properties properties; - private boolean writeProperties; - - public boolean hideServerScriptErrors; - public boolean serverOnly; - public boolean announceReload; - public boolean invertClassLoader; - public String packMode; - public boolean debugInfo; - - private CommonProperties() { - properties = new Properties(); - - try { - Path propertiesFile = KubeJSPaths.CONFIG.resolve("common.properties"); - writeProperties = false; - - if (Files.exists(propertiesFile)) { - try (Reader reader = Files.newBufferedReader(propertiesFile)) { - properties.load(reader); - } - } else { - writeProperties = true; - } - - hideServerScriptErrors = get("hideServerScriptErrors", false); - serverOnly = get("serverOnly", false); - announceReload = get("announceReload", true); - invertClassLoader = "true".equals(properties.getProperty("invertClassLoader")); // Advanced option, not recommended to be set to true - packMode = get("packmode", "default"); - debugInfo = get("debugInfo", false); - - if (writeProperties) { - try (Writer writer = Files.newBufferedWriter(propertiesFile)) { - properties.store(writer, "KubeJS Common Properties"); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - KubeJS.LOGGER.info("Loaded common.properties"); - } - - private void remove(String key) { - String s = properties.getProperty(key); - - if (s != null) { - properties.remove(key); - writeProperties = true; - } - } - - private String get(String key, String def) { - String s = properties.getProperty(key); - - if (s == null) { - properties.setProperty(key, def); - writeProperties = true; - return def; - } - - return s; - } - - private boolean get(String key, boolean def) { - return get(key, def ? "true" : "false").equals("true"); - } + private static CommonProperties INSTANCE; + + public static CommonProperties get() { + if (INSTANCE == null) { + INSTANCE = new CommonProperties(); + } + + return INSTANCE; + } + + public static void reload() { + INSTANCE = new CommonProperties(); + } + + private final Properties properties; + private boolean writeProperties; + + public boolean hideServerScriptErrors; + public boolean serverOnly; + public boolean announceReload; + public boolean invertClassLoader; + public String packMode; + public boolean debugInfo; + public boolean saveDevPropertiesInConfig; + public boolean allowAsyncStreams; + public boolean matchJsonRecipes; + public boolean ignoreCustomUniqueRecipeIds; + public boolean startupErrorGUI; + public String startupErrorReportUrl; + + private CommonProperties() { + properties = new Properties(); + + try { + writeProperties = false; + + if (Files.exists(KubeJSPaths.COMMON_PROPERTIES)) { + try (val reader = Files.newBufferedReader(KubeJSPaths.COMMON_PROPERTIES)) { + properties.load(reader); + } + } else { + writeProperties = true; + } + + hideServerScriptErrors = get("hideServerScriptErrors", false); + serverOnly = get("serverOnly", false); + announceReload = get("announceReload", true); + packMode = get("packmode", ""); + saveDevPropertiesInConfig = get("saveDevPropertiesInConfig", false); + allowAsyncStreams = get("allowAsyncStreams", true); + matchJsonRecipes = get("matchJsonRecipes", true); + ignoreCustomUniqueRecipeIds = get("ignoreCustomUniqueRecipeIds", false); + startupErrorGUI = get("startupErrorGUI", false); + startupErrorReportUrl = get("startupErrorReportUrl", ""); + + KubeJSPlugins.forEachPlugin(p -> p.loadCommonProperties(this)); + + if (writeProperties) { + save(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + KubeJS.LOGGER.info("Loaded common.properties"); + } + + public void remove(String key) { + val s = properties.getProperty(key); + + if (s != null) { + properties.remove(key); + writeProperties = true; + } + } + + public String get(String key, String def) { + val s = properties.getProperty(key); + + if (s == null) { + properties.setProperty(key, def); + writeProperties = true; + return def; + } + + return s; + } + + public boolean get(String key, boolean def) { + return get(key, def ? "true" : "false").equals("true"); + } + + public void save() { + try (val writer = Files.newBufferedWriter(KubeJSPaths.COMMON_PROPERTIES)) { + properties.store(writer, "KubeJS Common Properties"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public void setPackMode(String s) { + packMode = s; + properties.setProperty("packmode", s); + save(); + } } \ No newline at end of file diff --git a/common/src/main/java/dev/latvian/kubejs/DevProperties.java b/common/src/main/java/dev/latvian/kubejs/DevProperties.java new file mode 100644 index 000000000..928ce7bd5 --- /dev/null +++ b/common/src/main/java/dev/latvian/kubejs/DevProperties.java @@ -0,0 +1,115 @@ +package dev.latvian.kubejs; + +import lombok.val; +import me.shedaniel.architectury.platform.Platform; +import dev.latvian.kubejs.util.KubeJSPlugins; + +import java.io.Reader; +import java.io.Writer; +import java.nio.file.Files; +import java.util.Properties; + +public class DevProperties { + private static DevProperties instance; + + public static DevProperties get() { + if (instance == null) { + instance = new DevProperties(); + } + + return instance; + } + + public static void reload() { + instance = new DevProperties(); + } + + private final Properties properties; + private boolean writeProperties; + + public boolean debugInfo; + public boolean dataPackOutput = false; + public boolean logAddedRecipes = false; + public boolean logRemovedRecipes = false; + public boolean logModifiedRecipes = false; + public boolean logSkippedRecipes = false; + public boolean logSkippedTags = false; + public boolean logErroringRecipes = true; + public boolean logInvalidRecipeHandlers = true; + public boolean logSkippedPlugins = true; + public boolean logGeneratedData = false; + public boolean strictTags = false; + + private DevProperties() { + properties = new Properties(); + + try { + val propertiesFile = KubeJSPaths.getLocalDevProperties(); + writeProperties = false; + + if (Files.exists(propertiesFile)) { + try (Reader reader = Files.newBufferedReader(propertiesFile)) { + properties.load(reader); + } + } else { + writeProperties = true; + } + + debugInfo = get("debugInfo", Platform.isDevelopmentEnvironment()); + dataPackOutput = get("dataPackOutput", false); + logAddedRecipes = get("logAddedRecipes", false); + logRemovedRecipes = get("logRemovedRecipes", false); + logModifiedRecipes = get("logModifiedRecipes", false); + logSkippedRecipes = get("logSkippedRecipes", false); + logSkippedTags = get("logSkippedTags", false); + logErroringRecipes = get("logErroringRecipes", true); + logInvalidRecipeHandlers = get("logInvalidRecipeHandlers", true); + logSkippedPlugins = get("logSkippedPlugins", true); + logGeneratedData = get("logGeneratedData", false); + strictTags = get("strictTags", false); + + KubeJSPlugins.forEachPlugin(p -> p.loadDevProperties(this)); + + if (writeProperties) { + save(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + KubeJS.LOGGER.info("Loaded dev.properties"); + } + + public void remove(String key) { + val s = properties.getProperty(key); + + if (s != null) { + properties.remove(key); + writeProperties = true; + } + } + + public String get(String key, String def) { + val got = properties.getProperty(key); + + if (got == null) { + properties.setProperty(key, def); + writeProperties = true; + return def; + } + + return got; + } + + public boolean get(String key, boolean def) { + return get(key, def ? "true" : "false").equals("true"); + } + + public void save() { + try (Writer writer = Files.newBufferedWriter(KubeJSPaths.getLocalDevProperties())) { + properties.store(writer, "KubeJS Dev Properties"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/common/src/main/java/dev/latvian/kubejs/KubeJS.java b/common/src/main/java/dev/latvian/kubejs/KubeJS.java index edc4f7052..55328f210 100644 --- a/common/src/main/java/dev/latvian/kubejs/KubeJS.java +++ b/common/src/main/java/dev/latvian/kubejs/KubeJS.java @@ -1,5 +1,6 @@ package dev.latvian.kubejs; +import com.google.common.base.Stopwatch; import dev.latvian.kubejs.block.events.KubeJSBlockEventHandler; import dev.latvian.kubejs.client.KubeJSClient; import dev.latvian.kubejs.entity.KubeJSEntityEventHandler; @@ -25,8 +26,9 @@ import dev.latvian.kubejs.world.KubeJSWorldEventHandler; import dev.latvian.kubejs.world.gen.FlatChunkGeneratorKJS; import lombok.val; +import me.shedaniel.architectury.platform.Mod; import me.shedaniel.architectury.platform.Platform; -import me.shedaniel.architectury.utils.EnvExecutor; +import me.shedaniel.architectury.utils.Env; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.CreativeModeTab; @@ -40,7 +42,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; -import java.util.List; import java.util.Locale; /** @@ -50,6 +51,7 @@ public class KubeJS { public static final String MOD_ID = "kubejs"; public static final String MOD_NAME = "KubeJS"; public static final Logger LOGGER = LogManager.getLogger(MOD_NAME); + public static Mod thisMod; public static ResourceLocation id(String path) { return new ResourceLocation(MOD_ID, path); @@ -69,34 +71,42 @@ public static ResourceLocation id(String path) { public KubeJS() throws Throwable { instance = this; + thisMod = Platform.getMod(MOD_ID); Locale.setDefault(Locale.US); new KubeJSBackgroundThread().start(); if (Files.notExists(KubeJSPaths.README)) { - UtilsJS.tryIO(() -> { - List list = new ArrayList<>(); - list.add("Find more info on the website: https://kubejs.com/"); - list.add(""); - list.add("Directory information:"); - list.add(""); - list.add("assets - Acts as a resource pack, you can put any client resources in here, like textures, models, etc. Example: assets/kubejs/textures/item/test_item.png"); - list.add("data - Acts as a datapack, you can put any server resources in here, like loot tables, functions, etc. Example: data/kubejs/loot_tables/blocks/test_block.json"); - list.add(""); - list.add("startup_scripts - Scripts that get loaded once during game startup - Used for adding items and other things that can only happen while the game is loading (Can be reloaded with /kubejs reload_startup_scripts, but it may not work!)"); - list.add("server_scripts - Scripts that get loaded every time server resources reload - Used for modifying recipes, tags, loot tables, and handling server events (Can be reloaded with /reload)"); - list.add("client_scripts - Scripts that get loaded every time client resources reload - Used for JEI events, tooltips and other client side things (Can be reloaded with F3+T)"); - list.add(""); - list.add("config - KubeJS config storage. This is also the only directory that scripts can access other than world directory"); - list.add("exported - Data dumps like texture atlases end up here"); - list.add(""); - list.add("You can find type-specific logs in logs/kubejs/ directory"); - Files.write(KubeJSPaths.README, list); - }); + UtilsJS.tryIO(() -> Files.writeString(KubeJSPaths.README, """ + Find out more info on the website: https://kubejs.com/ + + Directory information: + + assets - Acts as a resource pack, you can put any client resources in here, like textures, models, etc. Example: assets/kubejs/textures/item/test_item.png + data - Acts as a datapack, you can put any server resources in here, like loot tables, functions, etc. Example: data/kubejs/loot_tables/blocks/test_block.json + + startup_scripts - Scripts that get loaded once during game startup - Used for adding items and other things that can only happen while the game is loading (Can be reloaded with '/kubejs reload startup_scripts') + server_scripts - Scripts that get loaded every time server resources reload - Used for modifying recipes, tags, loot tables, and handling server events (Can be reloaded with /reload or '/kubejs reload server_scripts') + client_scripts - Scripts that get loaded every time client resources reload - Used for JEI events, tooltips and other client side things (Can be reloaded with F3+T or '/kubejs reload client_scripts') + + config - KubeJS config storage. This is also the only directory that scripts can access other than world directory + exported - Data dumps like texture atlases end up here + + You can find type-specific logs in logs/kubejs/ directory""")); } - PROXY = EnvExecutor.getEnvSpecific(() -> KubeJSClient::new, () -> KubeJSCommon::new); + PROXY = Platform.getEnvironment() == Env.CLIENT + ? new KubeJSClient() + : new KubeJSCommon(); - KubeJSPlugins.initFromMods(); + { + val pluginTimer = Stopwatch.createStarted(); + LOGGER.info("Looking for KubeJS plugins..."); + val allMods = new ArrayList<>(Platform.getMods()); + allMods.remove(thisMod); + allMods.addFirst(thisMod); + KubeJSPlugins.load(allMods); + LOGGER.info("Done in {}", pluginTimer.stop()); + } startupScriptManager = new ScriptManager(ScriptType.STARTUP, KubeJSPaths.STARTUP_SCRIPTS, "/data/kubejs/example_startup_script.js"); clientScriptManager = new ScriptManager(ScriptType.CLIENT, KubeJSPaths.CLIENT_SCRIPTS, "/data/kubejs/example_client_script.js"); @@ -142,18 +152,22 @@ public static void loadScripts(ScriptPack pack, Path dir, String path) { val pathPrefix = path; - UtilsJS.tryIO(() -> Files - .walk(dir, 10) - .filter(Files::isRegularFile) - .map(file -> dir.relativize(file).toString().replace(File.separatorChar, '/')) - .filter(name -> name.endsWith(".js")) - .forEach(fileName -> pack.info.scripts.add(new ScriptFileInfo(pack.info, pathPrefix + fileName)))); - } + UtilsJS.tryIO(() -> Files + .walk(dir, 10) + .filter(Files::isRegularFile) + .map(file -> dir.relativize(file).toString().replace(File.separatorChar, '/')) + .filter(name -> name.endsWith(".js")) + .forEach(fileName -> pack.info.scripts.add(new ScriptFileInfo(pack.info, pathPrefix + fileName)))); + } public static String appendModId(String id) { return id.indexOf(':') == -1 ? (MOD_ID + ":" + id) : id; } + public static ResourceLocation rl(String path) { + return new ResourceLocation(MOD_ID, path); + } + public static Path getGameDirectory() { return Platform.getGameFolder(); } @@ -174,7 +188,7 @@ public void setup() { UtilsJS.init(); KubeJSNet.init(); new StartupEventJS().post(ScriptType.STARTUP, KubeJSEvents.INIT); - Registry.register(Registry.CHUNK_GENERATOR, new ResourceLocation(KubeJS.MOD_ID, "flat"), FlatChunkGeneratorKJS.CODEC); + Registry.register(Registry.CHUNK_GENERATOR, rl("flat"), FlatChunkGeneratorKJS.CODEC); //KubeJSRegistries.chunkGenerators().register(new ResourceLocation(KubeJS.MOD_ID, "flat"), () -> FlatChunkGeneratorKJS.CODEC); } diff --git a/common/src/main/java/dev/latvian/kubejs/KubeJSPaths.java b/common/src/main/java/dev/latvian/kubejs/KubeJSPaths.java index 247cab982..4c26ebeb3 100644 --- a/common/src/main/java/dev/latvian/kubejs/KubeJSPaths.java +++ b/common/src/main/java/dev/latvian/kubejs/KubeJSPaths.java @@ -3,6 +3,7 @@ import dev.latvian.kubejs.util.UtilsJS; import me.shedaniel.architectury.platform.Platform; import net.minecraft.server.packs.PackType; +import org.apache.commons.lang3.mutable.MutableBoolean; import java.nio.file.Files; import java.nio.file.Path; @@ -21,21 +22,56 @@ public class KubeJSPaths { public static final Path EXPORTED = DIRECTORY.resolve("exported"); public static final Path README = DIRECTORY.resolve("README.txt"); - static { - if (Files.notExists(DIRECTORY)) { - UtilsJS.tryIO(() -> Files.createDirectories(DIRECTORY)); - } + public static final Path COMMON_PROPERTIES = CONFIG.resolve("common.properties"); + public static final Path CLIENT_PROPERTIES = CONFIG.resolve("client.properties"); + public static final Path CONFIG_DEV_PROPERTIES = CONFIG.resolve("dev.properties"); + public static final Path LOCAL = dir(Platform.getGameFolder().resolve("local").resolve("kubejs")); + public static final Path LOCAL_CACHE = dir(LOCAL.resolve("cache")); + public static final Path LOCAL_DEV_PROPERTIES = LOCAL.resolve("dev.properties"); + public static final Path EXPORT = dir(LOCAL.resolve("export")); + public static final Path EXPORTED_PACKS = dir(LOCAL.resolve("exported_packs")); - if (Files.notExists(CONFIG)) { - UtilsJS.tryIO(() -> Files.createDirectories(CONFIG)); - } + public static final MutableBoolean FIRST_RUN = new MutableBoolean(false); + + static Path dir(Path dir, boolean markFirstRun) { + if (Files.exists(dir)) { + return dir; + } + + try { + Files.createDirectories(dir); + + if (markFirstRun) { + FIRST_RUN.setTrue(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } - if (Files.notExists(EXPORTED)) { - UtilsJS.tryIO(() -> Files.createDirectories(EXPORTED)); + return dir; + } + + public static Path dir(Path dir) { + return dir(dir, false); + } + + static { + createDirIfAbsent(DIRECTORY); + createDirIfAbsent(CONFIG); + createDirIfAbsent(EXPORTED); + } + + private static void createDirIfAbsent(Path directory) { + if (Files.notExists(directory)) { + UtilsJS.tryIO(() -> Files.createDirectories(directory)); } } public static Path get(PackType type) { return type == PackType.CLIENT_RESOURCES ? ASSETS : DATA; } + + static Path getLocalDevProperties() { + return CommonProperties.get().saveDevPropertiesInConfig ? CONFIG_DEV_PROPERTIES : LOCAL_DEV_PROPERTIES; + } } diff --git a/common/src/main/java/dev/latvian/kubejs/KubeJSPlugin.java b/common/src/main/java/dev/latvian/kubejs/KubeJSPlugin.java index 27bf99c52..db5a8028b 100644 --- a/common/src/main/java/dev/latvian/kubejs/KubeJSPlugin.java +++ b/common/src/main/java/dev/latvian/kubejs/KubeJSPlugin.java @@ -56,6 +56,12 @@ public void generateDataJsons(DataJsonGenerator generator) { public void generateAssetJsons(AssetJsonGenerator generator) { } - public void generateLang(Map lang) { + public void generateLang(Map enusLang) { } + + public void loadCommonProperties(CommonProperties properties) { + } + + public void loadDevProperties(DevProperties properties) { + } } diff --git a/common/src/main/java/dev/latvian/kubejs/bindings/TextWrapper.java b/common/src/main/java/dev/latvian/kubejs/bindings/TextWrapper.java index b1e1a12a5..155de1b0a 100644 --- a/common/src/main/java/dev/latvian/kubejs/bindings/TextWrapper.java +++ b/common/src/main/java/dev/latvian/kubejs/bindings/TextWrapper.java @@ -13,6 +13,7 @@ import dev.latvian.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.annotations.typing.JSInfo; import dev.latvian.mods.rhino.mod.wrapper.ColorWrapper; +import lombok.val; import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; import net.minecraft.network.chat.*; @@ -110,11 +111,11 @@ public static Text fromComponent(Component c) { if (c == null) { return new TextString("null"); } - var t = c instanceof TranslatableComponent transl + val t = c instanceof TranslatableComponent transl ? new TextTranslate(transl.getKey(), transl.getArgs()) : new TextString(c.getContents()); - var style = c.getStyle(); + val style = c.getStyle(); t.bold(style.isBold()) .color(ColorWrapper.of(style.getColor())) .font(style.getFont()) @@ -126,7 +127,7 @@ public static Text fromComponent(Component c) { .click(style.getClickEvent()) .hover(style.getHoverEvent()); - for (var sibling : c.getSiblings()) { + for (val sibling : c.getSiblings()) { t.append(fromComponent(sibling)); } @@ -239,25 +240,25 @@ public static ClickEvent clickEventOf(Object o) { return ce; } //json - var json = MapJS.json(o); + val json = MapJS.json(o); if (json != null) { - var action = GsonHelper.getAsString(json, "action"); - var value = GsonHelper.getAsString(json, "value"); + val action = GsonHelper.getAsString(json, "action"); + val value = GsonHelper.getAsString(json, "value"); return new ClickEvent( Objects.requireNonNull(ClickEvent.Action.getByName(action), "Invalid click event action " + action + "!"), value ); } //string - var s = o.toString(); - var split = s.split(":", 2); + val s = o.toString(); + val split = s.split(":", 2); return switch (split[0]) { case "command" -> new ClickEvent(ClickEvent.Action.RUN_COMMAND, split[1]); case "suggest_command" -> new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, split[1]); case "copy" -> new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, split[1]); case "file" -> new ClickEvent(ClickEvent.Action.OPEN_FILE, split[1]); default -> { - var action = ClickEvent.Action.getByName(split[0]); + val action = ClickEvent.Action.getByName(split[0]); if (action != null) { yield new ClickEvent(action, split[1]); } @@ -295,7 +296,7 @@ private static Text ofWrapped(@Nullable Object o) { ListJS a = map.getOrNewList("with"); with = new Object[a.size()]; for (int i = 0, size = a.size(); i < size; i++) { - var elem = a.get(i); + val elem = a.get(i); with[i] = elem instanceof MapJS || elem instanceof ListJS ? ofWrapped(elem) : elem; diff --git a/common/src/main/java/dev/latvian/kubejs/block/BlockBuilder.java b/common/src/main/java/dev/latvian/kubejs/block/BlockBuilder.java index f5a97d9d3..411dcb502 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/BlockBuilder.java +++ b/common/src/main/java/dev/latvian/kubejs/block/BlockBuilder.java @@ -270,7 +270,7 @@ public void generateDataJsons(DataJsonGenerator generator) { return; } - var lootBuilder = new LootBuilder(null); + val lootBuilder = new LootBuilder(null); lootBuilder.type = "minecraft:block"; if (lootTable != null) { @@ -282,7 +282,7 @@ public void generateDataJsons(DataJsonGenerator generator) { }); } - var json = lootBuilder.toJson(); + val json = lootBuilder.toJson(); generator.json(newID("loot_tables/blocks/", ""), json); } @@ -329,7 +329,7 @@ protected void generateBlockModelJsons(AssetJsonGenerator generator) { return; } generator.blockModel(id, mg -> { - var particle = textures.get("particle").getAsString(); + val particle = textures.get("particle").getAsString(); if (areAllTexturesEqual(textures, particle)) { mg.parent("minecraft:block/cube_all"); @@ -346,11 +346,11 @@ protected void generateBlockModelJsons(AssetJsonGenerator generator) { boxes.add(new AABB(0D, 0D, 0D, 1D, 1D, 1D)); } - for (var box : boxes) { + for (val box : boxes) { mg.element(e -> { e.box(box); - for (var direction : Direction.values()) { + for (val direction : Direction.values()) { e.face(direction, face -> { face.tex("#" + direction.getSerializedName()); face.cull(); @@ -371,7 +371,7 @@ protected void generateBlockStateJson(VariantBlockStateGenerator bs) { } protected boolean areAllTexturesEqual(JsonObject tex, String t) { - for (var direction : Direction.values()) { + for (val direction : Direction.values()) { if (!tex.get(direction.getSerializedName()).getAsString().equals(t)) { return false; } @@ -486,7 +486,7 @@ public static VoxelShape createShape(List boxes) { var shape = Shapes.create(boxes.get(0)); - for (var i = 1; i < boxes.size(); i++) { + for (int i = 1; i < boxes.size(); i++) { shape = Shapes.or(shape, Shapes.create(boxes.get(i))); } diff --git a/common/src/main/java/dev/latvian/kubejs/block/predicate/BlockStatePredicate.java b/common/src/main/java/dev/latvian/kubejs/block/BlockStatePredicate.java similarity index 98% rename from common/src/main/java/dev/latvian/kubejs/block/predicate/BlockStatePredicate.java rename to common/src/main/java/dev/latvian/kubejs/block/BlockStatePredicate.java index c0cfaebce..41dbddf6d 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/predicate/BlockStatePredicate.java +++ b/common/src/main/java/dev/latvian/kubejs/block/BlockStatePredicate.java @@ -1,6 +1,5 @@ -package dev.latvian.kubejs.block.predicate; +package dev.latvian.kubejs.block; -import com.github.bsideup.jabel.Desugar; import dev.latvian.kubejs.registry.RegistryInfos; import dev.latvian.kubejs.util.ListJS; import dev.latvian.kubejs.util.MapJS; @@ -32,6 +31,9 @@ import java.util.Set; import java.util.regex.Pattern; +/** + * ideally should be in {@link dev.latvian.kubejs.block.predicate}, but kept here for backward compat + */ @FunctionalInterface public interface BlockStatePredicate { ResourceLocation AIR_ID = new ResourceLocation("minecraft:air"); @@ -93,7 +95,7 @@ static BlockStatePredicate of(Object o) { } } - return predicates.isEmpty() ? Simple.NONE : predicates.size() == 1 ? predicates.get(0) : new OrMatch(predicates); + return predicates.isEmpty() ? Simple.NONE : predicates.size() == 1 ? predicates.getFirst() : new OrMatch(predicates); } val map = MapJS.of(o); @@ -210,7 +212,6 @@ public Collection getBlockStates() { } } - @Desugar record BlockMatch(Block block) implements BlockStatePredicate { @Override public boolean check(BlockState state) { @@ -244,7 +245,6 @@ public RuleTest asRuleTest() { } } - @Desugar record StateMatch(BlockState state) implements BlockStatePredicate { @Override public boolean check(BlockState s) { @@ -278,7 +278,6 @@ public RuleTest asRuleTest() { } } - @Desugar record TagMatch(Tag tag) implements BlockStatePredicate { @Override public boolean check(BlockState state) { @@ -301,7 +300,6 @@ public RuleTest asRuleTest() { } } - @Desugar final class RegexMatch implements BlockStatePredicate { public final Pattern pattern; private final LinkedHashSet matchedBlocks; @@ -343,7 +341,6 @@ public RuleTest asRuleTest() { } } - @Desugar record OrMatch(List list) implements BlockStatePredicate { @Override public boolean check(BlockState state) { @@ -410,7 +407,6 @@ public RuleTest asRuleTest() { } } - @Desugar final class NotMatch implements BlockStatePredicate { private final BlockStatePredicate predicate; private final Collection cachedStates; @@ -470,7 +466,6 @@ public RuleTest asRuleTest() { } } - @Desugar final class AndMatch implements BlockStatePredicate { private final List list; private final Collection cachedStates; @@ -481,7 +476,7 @@ public AndMatch(List list) { for (val entry : RegistryInfos.BLOCK.entrySet()) { for (val state : entry.getValue().getStateDefinition().getPossibleStates()) { - var match = true; + boolean match = true; for (val predicate : list) { if (!predicate.check(state)) { match = false; diff --git a/common/src/main/java/dev/latvian/kubejs/block/BlockTintFunction.java b/common/src/main/java/dev/latvian/kubejs/block/BlockTintFunction.java index ca4176387..1820cf47e 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/BlockTintFunction.java +++ b/common/src/main/java/dev/latvian/kubejs/block/BlockTintFunction.java @@ -1,8 +1,5 @@ package dev.latvian.kubejs.block; -import com.github.bsideup.jabel.Desugar; -import dev.latvian.mods.rhino.BaseFunction; -import dev.latvian.mods.rhino.NativeJavaObject; import dev.latvian.mods.rhino.Undefined; import dev.latvian.mods.rhino.mod.util.color.Color; import dev.latvian.mods.rhino.mod.util.color.SimpleColor; @@ -10,6 +7,7 @@ import dev.latvian.mods.rhino.mod.wrapper.ColorWrapper; import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import lombok.val; import net.minecraft.client.renderer.BiomeColors; import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockAndTintGetter; @@ -26,7 +24,6 @@ public interface BlockTintFunction { Color getColor(BlockState state, @Nullable BlockAndTintGetter level, @Nullable BlockPos pos, int index); - @Desugar record Fixed(Color color) implements BlockTintFunction { @Override public Color getColor(BlockState state, @Nullable BlockAndTintGetter level, @Nullable BlockPos pos, int index) { @@ -39,7 +36,7 @@ class Mapped implements BlockTintFunction { @Override public Color getColor(BlockState state, @Nullable BlockAndTintGetter level, @Nullable BlockPos pos, int index) { - var f = map.get(index); + val f = map.get(index); return f == null ? null : f.getColor(state, level, pos, index); } } @@ -70,10 +67,10 @@ static BlockTintFunction of(Object o) { } else if (o instanceof BlockTintFunction f) { return f; } else if (o instanceof List list) { - var map = new Mapped(); + val map = new Mapped(); for (int i = 0, size = list.size(); i < size; i++) { - var fn = of(list.get(i)); + val fn = of(list.get(i)); if (fn != null) { map.map.put(i, fn); } @@ -81,7 +78,7 @@ static BlockTintFunction of(Object o) { return map; } else if (o instanceof CharSequence) { - var fn = switch (o.toString()) { + val fn = switch (o.toString()) { case "grass" -> GRASS; case "foliage" -> FOLIAGE; case "evergreen_foliage" -> EVERGREEN_FOLIAGE; diff --git a/common/src/main/java/dev/latvian/kubejs/block/MapColorHelper.java b/common/src/main/java/dev/latvian/kubejs/block/MapColorHelper.java index 9e0740577..b4e9e50f7 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/MapColorHelper.java +++ b/common/src/main/java/dev/latvian/kubejs/block/MapColorHelper.java @@ -1,6 +1,5 @@ package dev.latvian.kubejs.block; -import com.github.bsideup.jabel.Desugar; import com.mojang.math.Vector3f; import dev.latvian.kubejs.bindings.KMath; import dev.latvian.mods.rhino.Undefined; @@ -13,7 +12,6 @@ import java.util.Map; import java.util.function.Function; -@Desugar public record MapColorHelper(int id, String name, MaterialColor color, Vector3f rgb) implements Function { public static final Map NAME_MAP = new HashMap<>(96); public static final Map ID_MAP = new HashMap<>(96); @@ -97,7 +95,7 @@ public static MaterialColor of(Object o) { } else if (o instanceof MaterialColor c) { return c; } else if (o instanceof CharSequence s) { - if (s.length() == 0) { + if (s.isEmpty()) { return MaterialColor.NONE; } else if (s.charAt(0) == '#') { return findClosest(Integer.decode(s.toString())).color; @@ -120,7 +118,7 @@ public static MapColorHelper reverse(MaterialColor c) { public static MapColorHelper findClosest(int rgbi) { val rgb = new Vector3f((rgbi >> 16 & 0xFF) / 255F, (rgbi >> 8 & 0xFF) / 255F, (rgbi & 0xFF) / 255F); MapColorHelper closest = null; - var lastDist = Float.MAX_VALUE; + float lastDist = Float.MAX_VALUE; for (val helper : NAME_MAP.values()) { if (helper.color != MaterialColor.NONE) { diff --git a/common/src/main/java/dev/latvian/kubejs/block/custom/DetectorBlock.java b/common/src/main/java/dev/latvian/kubejs/block/custom/DetectorBlock.java index 829804773..ce91be1e8 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/custom/DetectorBlock.java +++ b/common/src/main/java/dev/latvian/kubejs/block/custom/DetectorBlock.java @@ -5,6 +5,7 @@ import dev.latvian.kubejs.block.BlockBuilder; import dev.latvian.kubejs.block.events.DetectorBlockEventJS; import dev.latvian.kubejs.generator.AssetJsonGenerator; +import lombok.val; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.Level; @@ -61,7 +62,7 @@ public void neighborChanged(BlockState blockState, Level level, BlockPos blockPo if (level.isClientSide) { return; } - var p = !blockState.getValue(BlockStateProperties.POWERED); + val p = !blockState.getValue(BlockStateProperties.POWERED); if (p == level.hasNeighborSignal(blockPos)) { level.setBlock(blockPos, blockState.setValue(BlockStateProperties.POWERED, p), 2); diff --git a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/ButtonBlockBuilder.java b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/ButtonBlockBuilder.java index 7e38554c6..7c26fde1e 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/ButtonBlockBuilder.java +++ b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/ButtonBlockBuilder.java @@ -5,6 +5,7 @@ import dev.latvian.kubejs.client.ModelGenerator; import dev.latvian.kubejs.client.VariantBlockStateGenerator; import dev.latvian.kubejs.generator.AssetJsonGenerator; +import lombok.val; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Block; @@ -35,8 +36,8 @@ public Block createObject() { @Override protected void generateBlockStateJson(VariantBlockStateGenerator bs) { - var mod0 = newID("block/", "").toString(); - var mod1 = newID("block/", "_pressed").toString(); + val mod0 = newID("block/", "").toString(); + val mod1 = newID("block/", "_pressed").toString(); bs.variant("face=ceiling,facing=east,powered=false", v -> v.model(mod0).x(180).y(270)); bs.variant("face=ceiling,facing=east,powered=true", v -> v.model(mod1).x(180).y(270)); @@ -66,7 +67,7 @@ protected void generateBlockStateJson(VariantBlockStateGenerator bs) { @Override protected void generateBlockModelJsons(AssetJsonGenerator generator) { - var texture = textures.get("texture").getAsString(); + val texture = textures.get("texture").getAsString(); generator.blockModel(id, m -> { m.parent("minecraft:block/button"); diff --git a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/CropBlockBuilder.java b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/CropBlockBuilder.java index d511c099c..79e6c39a7 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/CropBlockBuilder.java +++ b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/CropBlockBuilder.java @@ -13,6 +13,7 @@ import dev.latvian.kubejs.item.custom.SeedItemBuilder; import dev.latvian.kubejs.world.BlockContainerJS; import dev.latvian.mods.rhino.annotations.typing.JSInfo; +import lombok.val; import me.shedaniel.architectury.platform.Platform; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; @@ -95,18 +96,18 @@ public CropBlockBuilder(ResourceLocation i) { //This should work as a minimum crop-like table lootTable = loot -> { - var condition = new JsonObject(); + val condition = new JsonObject(); condition.addProperty("condition", "minecraft:block_state_property"); condition.addProperty("block", this.newID("", "").toString()); - var properties = new JsonObject(); + val properties = new JsonObject(); properties.addProperty("age", String.valueOf(this.age)); condition.add("properties", properties); - var function = new JsonObject(); + val function = new JsonObject(); function.addProperty("function", "minecraft:apply_bonus"); function.addProperty("enchantment", "minecraft:fortune"); function.addProperty("formula", "minecraft:binomial_with_bonus_count"); - var parameters = new JsonObject(); + val parameters = new JsonObject(); parameters.addProperty("extra", 3); parameters.addProperty("probability", 0.5714286); //Same as vanilla function.add("parameters", parameters); diff --git a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/FenceBlockBuilder.java b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/FenceBlockBuilder.java index 2cac5e388..67108b281 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/FenceBlockBuilder.java +++ b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/FenceBlockBuilder.java @@ -3,6 +3,7 @@ import dev.latvian.kubejs.client.ModelGenerator; import dev.latvian.kubejs.client.MultipartBlockStateGenerator; import dev.latvian.kubejs.generator.AssetJsonGenerator; +import lombok.val; import me.shedaniel.architectury.platform.Platform; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; @@ -27,8 +28,8 @@ public Block createObject() { @Override protected void generateMultipartBlockStateJson(MultipartBlockStateGenerator bs) { - var modPost = newID("block/", "_post").toString(); - var modSide = newID("block/", "_side").toString(); + val modPost = newID("block/", "_post").toString(); + val modSide = newID("block/", "_side").toString(); bs.part("", modPost); bs.part("north=true", p -> p.model(modSide).uvlock()); @@ -45,7 +46,7 @@ protected void generateItemModelJson(ModelGenerator m) { @Override protected void generateBlockModelJsons(AssetJsonGenerator generator) { - var texture = textures.get("texture").getAsString(); + val texture = textures.get("texture").getAsString(); generator.blockModel(newID("", "_post"), m -> { m.parent("minecraft:block/fence_post"); diff --git a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/FenceGateBlockBuilder.java b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/FenceGateBlockBuilder.java index 7bd783a80..763d61b0c 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/FenceGateBlockBuilder.java +++ b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/FenceGateBlockBuilder.java @@ -3,6 +3,7 @@ import dev.latvian.kubejs.client.ModelGenerator; import dev.latvian.kubejs.client.VariantBlockStateGenerator; import dev.latvian.kubejs.generator.AssetJsonGenerator; +import lombok.val; import me.shedaniel.architectury.platform.Platform; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; @@ -32,7 +33,7 @@ public FenceGateBlockBuilder behaviour(WoodType wt) { } public FenceGateBlockBuilder behaviour(String wt) { - for (var type : WoodType.values().collect(Collectors.toList())) { + for (val type : WoodType.values().collect(Collectors.toList())) { if (type.name().equals(wt)) { behaviour = type; return this; @@ -49,10 +50,10 @@ public Block createObject() { @Override protected void generateBlockStateJson(VariantBlockStateGenerator bs) { - var mod = newID("block/", "").toString(); - var modOpen = newID("block/", "_open").toString(); - var modWall = newID("block/", "_wall").toString(); - var modWallOpen = newID("block/", "_wall_open").toString(); + val mod = newID("block/", "").toString(); + val modOpen = newID("block/", "_open").toString(); + val modWall = newID("block/", "_wall").toString(); + val modWallOpen = newID("block/", "_wall_open").toString(); bs.variant("facing=east,in_wall=false,open=false", v -> v.model(mod).y(270).uvlock()); bs.variant("facing=east,in_wall=false,open=true", v -> v.model(modOpen).y(270).uvlock()); @@ -74,7 +75,7 @@ protected void generateBlockStateJson(VariantBlockStateGenerator bs) { @Override protected void generateBlockModelJsons(AssetJsonGenerator generator) { - var texture = textures.get("texture").getAsString(); + val texture = textures.get("texture").getAsString(); generator.blockModel(id, m -> { m.parent("minecraft:block/template_fence_gate"); diff --git a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/HorizontalDirectionalBlockBuilder.java b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/HorizontalDirectionalBlockBuilder.java index d2a8059ab..d78cc3050 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/HorizontalDirectionalBlockBuilder.java +++ b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/HorizontalDirectionalBlockBuilder.java @@ -38,7 +38,7 @@ public HorizontalDirectionalBlockBuilder(ResourceLocation i) { @Override protected void generateBlockStateJson(VariantBlockStateGenerator bs) { - var modelLocation = model.isEmpty() ? newID("block/", "").toString() : model; + val modelLocation = model.isEmpty() ? newID("block/", "").toString() : model; bs.variant("facing=north", v -> v.model(modelLocation)); bs.variant("facing=east", v -> v.model(modelLocation).y(90)); bs.variant("facing=south", v -> v.model(modelLocation).y(180)); @@ -48,7 +48,7 @@ protected void generateBlockStateJson(VariantBlockStateGenerator bs) { @Override protected void generateBlockModelJsons(AssetJsonGenerator gen) { gen.blockModel(id, mg -> { - var side = getTextureOrDefault("side", newID("block/", "").toString()); + val side = getTextureOrDefault("side", newID("block/", "").toString()); mg.texture("side", side); mg.texture("front", getTextureOrDefault("front", newID("block/", "_front").toString())); diff --git a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/PressurePlateBlockBuilder.java b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/PressurePlateBlockBuilder.java index b28d17e8f..2a922c349 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/PressurePlateBlockBuilder.java +++ b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/PressurePlateBlockBuilder.java @@ -3,6 +3,7 @@ import dev.latvian.kubejs.client.ModelGenerator; import dev.latvian.kubejs.client.VariantBlockStateGenerator; import dev.latvian.kubejs.generator.AssetJsonGenerator; +import lombok.val; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Block; @@ -36,7 +37,7 @@ protected void generateBlockStateJson(VariantBlockStateGenerator bs) { @Override protected void generateBlockModelJsons(AssetJsonGenerator generator) { - var texture = textures.get("texture").getAsString(); + val texture = textures.get("texture").getAsString(); generator.blockModel(newID("", "_down"), m -> { m.parent("minecraft:block/pressure_plate_down"); diff --git a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/SlabBlockBuilder.java b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/SlabBlockBuilder.java index ae12b99bf..84614b725 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/SlabBlockBuilder.java +++ b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/SlabBlockBuilder.java @@ -3,6 +3,7 @@ import dev.latvian.kubejs.client.ModelGenerator; import dev.latvian.kubejs.client.VariantBlockStateGenerator; import dev.latvian.kubejs.generator.AssetJsonGenerator; +import lombok.val; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Block; @@ -28,7 +29,7 @@ protected void generateBlockStateJson(VariantBlockStateGenerator bs) { @Override protected void generateBlockModelJsons(AssetJsonGenerator generator) { - final var texture = textures.get("texture").getAsString(); + val texture = textures.get("texture").getAsString(); generator.blockModel(newID("", "_double"), m -> { m.parent("minecraft:block/cube_all"); diff --git a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/StairBlockBuilder.java b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/StairBlockBuilder.java index 889d353cd..b5a95165e 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/StairBlockBuilder.java +++ b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/StairBlockBuilder.java @@ -3,6 +3,7 @@ import dev.latvian.kubejs.block.custom.StairBlockJS; import dev.latvian.kubejs.client.VariantBlockStateGenerator; import dev.latvian.kubejs.generator.AssetJsonGenerator; +import lombok.val; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Block; @@ -20,9 +21,9 @@ public Block createObject() { @Override protected void generateBlockStateJson(VariantBlockStateGenerator bs) { - var mod = newID("block/", "").toString(); - var modInner = newID("block/", "_inner").toString(); - var modOuter = newID("block/", "_outer").toString(); + val mod = newID("block/", "").toString(); + val modInner = newID("block/", "_inner").toString(); + val modOuter = newID("block/", "_outer").toString(); bs.variant("facing=east,half=bottom,shape=inner_left", v -> v.model(modInner).y(270).uvlock()); bs.variant("facing=east,half=bottom,shape=inner_right", v -> v.model(modInner)); @@ -68,7 +69,7 @@ protected void generateBlockStateJson(VariantBlockStateGenerator bs) { @Override protected void generateBlockModelJsons(AssetJsonGenerator generator) { - var texture = textures.get("texture").getAsString(); + val texture = textures.get("texture").getAsString(); generator.blockModel(id, m -> { m.parent("minecraft:block/stairs"); diff --git a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/WallBlockBuilder.java b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/WallBlockBuilder.java index de8015c5e..40451122a 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/custom/builder/WallBlockBuilder.java +++ b/common/src/main/java/dev/latvian/kubejs/block/custom/builder/WallBlockBuilder.java @@ -3,6 +3,7 @@ import dev.latvian.kubejs.client.ModelGenerator; import dev.latvian.kubejs.client.MultipartBlockStateGenerator; import dev.latvian.kubejs.generator.AssetJsonGenerator; +import lombok.val; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Block; @@ -21,9 +22,9 @@ public Block createObject() { @Override protected void generateMultipartBlockStateJson(MultipartBlockStateGenerator bs) { - var modPost = newID("block/", "_post").toString(); - var modSide = newID("block/", "_side").toString(); - var modSideTall = newID("block/", "_side_tall").toString(); + val modPost = newID("block/", "_post").toString(); + val modSide = newID("block/", "_side").toString(); + val modSideTall = newID("block/", "_side_tall").toString(); bs.part("up=true", modPost); bs.part("north=low", p -> p.model(modSide).uvlock()); @@ -44,7 +45,7 @@ protected void generateItemModelJson(ModelGenerator m) { @Override protected void generateBlockModelJsons(AssetJsonGenerator generator) { - var texture = textures.get("texture").getAsString(); + val texture = textures.get("texture").getAsString(); generator.blockModel(newID("", "_post"), m -> { m.parent("minecraft:block/template_wall_post"); diff --git a/common/src/main/java/dev/latvian/kubejs/block/events/BlockModificationEventJS.java b/common/src/main/java/dev/latvian/kubejs/block/events/BlockModificationEventJS.java index 0f4a1aae5..b081a2665 100644 --- a/common/src/main/java/dev/latvian/kubejs/block/events/BlockModificationEventJS.java +++ b/common/src/main/java/dev/latvian/kubejs/block/events/BlockModificationEventJS.java @@ -1,7 +1,7 @@ package dev.latvian.kubejs.block.events; import dev.latvian.kubejs.block.BlockModificationProperties; -import dev.latvian.kubejs.block.predicate.BlockStatePredicate; +import dev.latvian.kubejs.block.BlockStatePredicate; import dev.latvian.kubejs.core.BlockKJS; import dev.latvian.kubejs.event.EventJS; import net.minecraft.world.level.block.Block; diff --git a/common/src/main/java/dev/latvian/kubejs/client/KubeJSClient.java b/common/src/main/java/dev/latvian/kubejs/client/KubeJSClient.java index 47a3170f4..746629085 100644 --- a/common/src/main/java/dev/latvian/kubejs/client/KubeJSClient.java +++ b/common/src/main/java/dev/latvian/kubejs/client/KubeJSClient.java @@ -14,6 +14,7 @@ import dev.latvian.mods.rhino.util.unit.FixedUnit; import dev.latvian.mods.rhino.util.unit.Unit; import dev.latvian.mods.rhino.util.wrap.TypeWrappers; +import lombok.val; import me.shedaniel.architectury.hooks.PackRepositoryHooks; import net.minecraft.Util; import net.minecraft.client.Minecraft; @@ -39,15 +40,14 @@ public class KubeJSClient extends KubeJSCommon { @Override public void init() { - if (Minecraft.getInstance() == null) // You'd think that this is impossible, but not when you use runData gradle task - { - return; - } + if (Minecraft.getInstance() == null) { + return;// You'd think that this is impossible, but not when you use runData gradle task + } reloadClientScripts(); new KubeJSClientEventHandler().init(); - PackRepository list = Minecraft.getInstance().getResourcePackRepository(); + val list = Minecraft.getInstance().getResourcePackRepository(); PackRepositoryHooks.addSource(list, new KubeJSResourcePackFinder()); setup(); @@ -68,7 +68,7 @@ public static void reloadClientScripts() { public static void copyDefaultOptionsFile(File optionsFile) { if (!optionsFile.exists()) { - Path defOptions = KubeJSPaths.CONFIG.resolve("defaultoptions.txt"); + val defOptions = KubeJSPaths.CONFIG.resolve("defaultoptions.txt"); if (Files.exists(defOptions)) { try { @@ -130,8 +130,15 @@ public WorldJS getClientWorld() { private void reload(PreparableReloadListener listener) { long start = System.currentTimeMillis(); - Minecraft mc = Minecraft.getInstance(); - listener.reload(CompletableFuture::completedFuture, mc.getResourceManager(), InactiveProfiler.INSTANCE, InactiveProfiler.INSTANCE, Util.backgroundExecutor(), mc).thenAccept(unused -> { + val mc = Minecraft.getInstance(); + listener.reload( + CompletableFuture::completedFuture, + mc.getResourceManager(), + InactiveProfiler.INSTANCE, + InactiveProfiler.INSTANCE, + Util.backgroundExecutor(), + mc + ).thenAccept(unused -> { /* long ms = System.currentTimeMillis() - start; @@ -142,8 +149,10 @@ private void reload(PreparableReloadListener listener) { } */ - mc.player.sendMessage(new TextComponent("Done! You still may have to reload all assets with F3 + T"), Util.NIL_UUID); - }); + if (mc.player != null) { + mc.player.sendMessage(new TextComponent("Done! You still may have to reload all assets with F3 + T"), Util.NIL_UUID); + } + }); } @Override diff --git a/common/src/main/java/dev/latvian/kubejs/client/KubeJSClientEventHandler.java b/common/src/main/java/dev/latvian/kubejs/client/KubeJSClientEventHandler.java index 5fe4e6358..2448ace1e 100644 --- a/common/src/main/java/dev/latvian/kubejs/client/KubeJSClientEventHandler.java +++ b/common/src/main/java/dev/latvian/kubejs/client/KubeJSClientEventHandler.java @@ -5,6 +5,7 @@ import dev.latvian.kubejs.KubeJSPaths; import dev.latvian.kubejs.block.BlockBuilder; import dev.latvian.kubejs.client.asset.AtlasSpriteRegistryEventJS; +import dev.latvian.kubejs.client.error.KubeJSErrorScreen; import dev.latvian.kubejs.client.painter.Painter; import dev.latvian.kubejs.client.painter.world.WorldPaintEventJS; import dev.latvian.kubejs.client.painter.world.WorldPainterObject; @@ -15,7 +16,6 @@ import dev.latvian.kubejs.item.events.ItemTooltipEventJS; import dev.latvian.kubejs.item.OldItemTooltipEventJS; import dev.latvian.kubejs.player.AttachPlayerDataEvent; -import dev.latvian.kubejs.registry.BuilderBase; import dev.latvian.kubejs.registry.RegistryInfos; import dev.latvian.kubejs.script.ScriptType; import dev.latvian.kubejs.util.Tags; @@ -35,19 +35,20 @@ import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.TitleScreen; import net.minecraft.client.gui.screens.recipebook.RecipeUpdateListener; import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.SpawnEggItem; import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.block.Block; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -87,12 +88,13 @@ public void init() { GuiEvent.RENDER_HUD.register(Painter.INSTANCE::inGameScreenDraw); GuiEvent.RENDER_POST.register(Painter.INSTANCE::guiScreenDraw); GuiEvent.INIT_POST.register(this::guiPostInit); + GuiEvent.SET_SCREEN.register(this::setScreen); TextureStitchEvent.PRE.register(this::preAtlasStitch); TextureStitchEvent.POST.register(this::postAtlasStitch); } private void preAtlasStitch(TextureAtlas atlas, Consumer consumer) { - var stitchEvent = new AtlasSpriteRegistryEventJS(consumer); + val stitchEvent = new AtlasSpriteRegistryEventJS(consumer); for (val builder : RegistryInfos.FLUID) { if (builder instanceof FluidBuilder f) { stitchEvent.register(ResourceLocation.tryParse(f.flowingTexture)); @@ -131,6 +133,16 @@ private void renderLayers() { } } + public InteractionResultHolder setScreen(Screen screen) { + if (screen instanceof TitleScreen + && !ScriptType.STARTUP.errors.isEmpty() + && !KubeJSErrorScreen.used + ) { + return InteractionResultHolder.success(new KubeJSErrorScreen(ScriptType.STARTUP, screen, true)); + } + return InteractionResultHolder.pass(null); + } + private void debugInfoLeft(List lines) { if (Minecraft.getInstance().player != null) { new DebugInfoEventJS(lines).post(ScriptType.CLIENT, KubeJSEvents.CLIENT_DEBUG_INFO_LEFT); diff --git a/common/src/main/java/dev/latvian/kubejs/client/KubeJSClientResourcePack.java b/common/src/main/java/dev/latvian/kubejs/client/KubeJSClientResourcePack.java index 4bffda4e1..f6b1ba65f 100644 --- a/common/src/main/java/dev/latvian/kubejs/client/KubeJSClientResourcePack.java +++ b/common/src/main/java/dev/latvian/kubejs/client/KubeJSClientResourcePack.java @@ -1,6 +1,5 @@ package dev.latvian.kubejs.client; -import com.google.gson.JsonElement; import dev.latvian.kubejs.KubeJS; import dev.latvian.kubejs.KubeJSEvents; import dev.latvian.kubejs.KubeJSPaths; @@ -9,98 +8,86 @@ import dev.latvian.kubejs.generator.AssetJsonGenerator; import dev.latvian.kubejs.registry.RegistryInfos; import dev.latvian.kubejs.script.ScriptType; +import dev.latvian.kubejs.script.data.GeneratedData; import dev.latvian.kubejs.script.data.KubeJSResourcePack; import dev.latvian.kubejs.util.KubeJSPlugins; import dev.latvian.mods.rhino.mod.util.JsonUtils; import lombok.val; import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.FilePackResources; -import net.minecraft.server.packs.PackResources; import net.minecraft.server.packs.PackType; import java.nio.file.Files; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; -import java.util.stream.Collectors; public class KubeJSClientResourcePack extends KubeJSResourcePack { - public static List inject(List packs) { - if (KubeJS.instance == null) { - return packs; - } - List injected = new ArrayList<>(packs); - //KubeJS injected resources should have lower priority then user resources packs, which means file pack - int pos = injected.size(); - for (int i = 0; i < pos; i++) { - if (injected.get(i) instanceof FilePackResources) { - pos = i; - break; - } - } - injected.add(pos, new KubeJSClientResourcePack()); - return injected; - } public KubeJSClientResourcePack() { super(PackType.CLIENT_RESOURCES); } @Override - public void generateJsonFiles(Map map) { - AssetJsonGenerator generator = new AssetJsonGenerator(map); + public void generate(Map map) { + val generator = new AssetJsonGenerator(map); + KubeJSPlugins.forEachPlugin(p -> p.generateAssetJsons(generator)); + new GenerateClientAssetsEventJS(generator).post(ScriptType.CLIENT, KubeJSEvents.CLIENT_GENERATE_ASSET); + generateLang(generator); } private void generateLang(AssetJsonGenerator generator) { - var langEvent = new LangEventJS(); + val langEvent = new LangEventJS(); - for (var builder : RegistryInfos.ALL_BUILDERS) { + for (val builder : RegistryInfos.ALL_BUILDERS) { builder.generateLang(langEvent); } - Map langMap = new HashMap<>(); - KubeJSPlugins.forEachPlugin(p -> p.generateLang(langMap)); - - new GenerateClientAssetsEventJS(generator).post(ScriptType.CLIENT, KubeJSEvents.CLIENT_GENERATE_ASSET); + Map enusLangMap = new HashMap<>(); + KubeJSPlugins.forEachPlugin(p -> p.generateLang(enusLangMap)); + //using a special namespace to keep backward equivalence + langEvent.get("kubejs_generated", "en_us").addAll(enusLangMap); //read lang json and add into lang event try (val in = Files.list(KubeJSPaths.ASSETS)) { - for (val dir : in.filter(Files::isDirectory).collect(Collectors.toList())) { + for (val dir : in.filter(Files::isDirectory).toList()) { val langDir = dir.resolve("lang"); if (!Files.exists(langDir) || !Files.isDirectory(langDir)) { continue; } + val namespace = dir.getFileName().toString(); - for (val path : Files.list(langDir).filter(Files::isRegularFile).filter(Files::isReadable).collect(Collectors.toList())) { + for (val path : Files.list(langDir).filter(Files::isRegularFile).filter(Files::isReadable).toList()) { val fileName = path.getFileName().toString(); if (!fileName.endsWith(".json")) { continue; } + try (val reader = Files.newBufferedReader(path)) { - val json = JsonUtils.GSON.fromJson(reader, Map.class); - val lang = fileName.substring(0, fileName.length() - 5); - langEvent.get(namespace, lang).addAll(json); + val lang = fileName.substring(0, fileName.length() - ".json".length()); + langEvent.get(namespace, lang) + .addAll(JsonUtils.GSON.fromJson(reader, Map.class)); } catch (Exception ex) { - ex.printStackTrace(); + KubeJS.LOGGER.error(ex); } } } } catch (Exception ex) { - ex.printStackTrace(); + KubeJS.LOGGER.error(ex); } - //using a special namespace to keep backward equivalence - langEvent.get("kubejs_generated", "en_us").addAll(langMap); langEvent.post(ScriptType.CLIENT, KubeJSEvents.CLIENT_LANG); for (val lang2entries : langEvent.namespace2lang2entries.values()) { for (val entries : lang2entries.values()) { - generator.json(entries.path(), entries.asJson()); + generator.json(entries.toPath(), entries.toJson()); } } } + + @Override + protected boolean skipFile(GeneratedData data) { + return data.id().getPath().startsWith("lang/"); + } } diff --git a/common/src/main/java/dev/latvian/kubejs/client/KubeJSResourcePackFinder.java b/common/src/main/java/dev/latvian/kubejs/client/KubeJSResourcePackFinder.java index b5de928fb..5f6d748e7 100644 --- a/common/src/main/java/dev/latvian/kubejs/client/KubeJSResourcePackFinder.java +++ b/common/src/main/java/dev/latvian/kubejs/client/KubeJSResourcePackFinder.java @@ -3,12 +3,10 @@ import dev.latvian.kubejs.KubeJS; import dev.latvian.kubejs.KubeJSPaths; import dev.latvian.kubejs.util.UtilsJS; +import lombok.val; import net.minecraft.server.packs.repository.Pack; import net.minecraft.server.packs.repository.RepositorySource; -import org.apache.commons.io.IOUtils; -import java.io.InputStream; -import java.io.OutputStream; import java.nio.file.Files; import java.util.function.Consumer; @@ -23,16 +21,16 @@ public void loadPacks(Consumer nameToPackMap, Pack.PackConstructor packInf UtilsJS.tryIO(() -> Files.createDirectories(KubeJSPaths.ASSETS.resolve("kubejs/textures/block"))); UtilsJS.tryIO(() -> Files.createDirectories(KubeJSPaths.ASSETS.resolve("kubejs/textures/item"))); - try (InputStream in = KubeJS.class.getResourceAsStream("/data/kubejs/example_block_texture.png"); - OutputStream out = Files.newOutputStream(KubeJSPaths.ASSETS.resolve("kubejs/textures/block/example_block.png"))) { - out.write(IOUtils.toByteArray(in)); + try (val in = KubeJS.class.getResourceAsStream("/data/kubejs/example_block_texture.png"); + val out = Files.newOutputStream(KubeJSPaths.ASSETS.resolve("kubejs/textures/block/example_block.png"))) { + in.transferTo(out); } catch (Exception ex) { ex.printStackTrace(); } - try (InputStream in = KubeJS.class.getResourceAsStream("/data/kubejs/example_item_texture.png"); - OutputStream out = Files.newOutputStream(KubeJSPaths.ASSETS.resolve("kubejs/textures/item/example_item.png"))) { - out.write(IOUtils.toByteArray(in)); + try (val in = KubeJS.class.getResourceAsStream("/data/kubejs/example_item_texture.png"); + val out = Files.newOutputStream(KubeJSPaths.ASSETS.resolve("kubejs/textures/item/example_item.png"))) { + in.transferTo(out); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/common/src/main/java/dev/latvian/kubejs/client/asset/GenerateClientAssetsEventJS.java b/common/src/main/java/dev/latvian/kubejs/client/asset/GenerateClientAssetsEventJS.java index f80b151ed..470cc50e1 100644 --- a/common/src/main/java/dev/latvian/kubejs/client/asset/GenerateClientAssetsEventJS.java +++ b/common/src/main/java/dev/latvian/kubejs/client/asset/GenerateClientAssetsEventJS.java @@ -6,6 +6,7 @@ import dev.latvian.kubejs.client.VariantBlockStateGenerator; import dev.latvian.kubejs.event.EventJS; import dev.latvian.kubejs.generator.AssetJsonGenerator; +import lombok.val; import net.minecraft.Util; import net.minecraft.resources.ResourceLocation; @@ -23,17 +24,17 @@ public void add(ResourceLocation location, JsonElement json) { } public void addModel(String type, ResourceLocation id, Consumer consumer) { - var gen = Util.make(new ModelGenerator(), consumer); + val gen = Util.make(new ModelGenerator(), consumer); add(new ResourceLocation(id.getNamespace(), String.format("models/%s/%s", type, id.getPath())), gen.toJson()); } public void addBlockState(ResourceLocation id, Consumer consumer) { - var gen = Util.make(new VariantBlockStateGenerator(), consumer); + val gen = Util.make(new VariantBlockStateGenerator(), consumer); add(new ResourceLocation(id.getNamespace(), "blockstates/" + id.getPath()), gen.toJson()); } public void addMultipartBlockState(ResourceLocation id, Consumer consumer) { - var gen = Util.make(new MultipartBlockStateGenerator(), consumer); + val gen = Util.make(new MultipartBlockStateGenerator(), consumer); add(new ResourceLocation(id.getNamespace(), "blockstates/" + id.getPath()), gen.toJson()); } diff --git a/common/src/main/java/dev/latvian/kubejs/client/asset/LangEntry.java b/common/src/main/java/dev/latvian/kubejs/client/asset/LangEntry.java index 00dc55f01..ea939685e 100644 --- a/common/src/main/java/dev/latvian/kubejs/client/asset/LangEntry.java +++ b/common/src/main/java/dev/latvian/kubejs/client/asset/LangEntry.java @@ -1,8 +1,8 @@ package dev.latvian.kubejs.client.asset; -import com.github.bsideup.jabel.Desugar; import com.google.gson.JsonObject; import dev.latvian.mods.rhino.annotations.typing.JSInfo; +import lombok.val; import net.minecraft.resources.ResourceLocation; import java.util.HashMap; @@ -11,7 +11,6 @@ /** * @author ZZZank */ -@Desugar public record LangEntry(String namespace, String lang, Map entries) { public LangEntry(String namespace, String lang) { this(namespace, lang, new HashMap<>()); @@ -23,7 +22,7 @@ public void add(String key, String text) { } public void addAll(Map map) { - for (var entry : map.entrySet()) { + for (val entry : map.entrySet()) { add(entry.getKey(), entry.getValue()); } } @@ -33,16 +32,16 @@ public void addIfAbsent(String key, String text) { entries.putIfAbsent(key, text); } - public JsonObject asJson() { - JsonObject obj = new JsonObject(); - for (var entry : entries.entrySet()) { + public JsonObject toJson() { + val obj = new JsonObject(); + for (val entry : entries.entrySet()) { obj.addProperty(entry.getKey(), entry.getValue()); } return obj; } @JSInfo("`{namespace}:lang/{lang}`") - public ResourceLocation path() { + public ResourceLocation toPath() { return new ResourceLocation(namespace, "lang/" + lang); } diff --git a/common/src/main/java/dev/latvian/kubejs/client/asset/LangEventJS.java b/common/src/main/java/dev/latvian/kubejs/client/asset/LangEventJS.java index b9dfaf4f7..500f50c8d 100644 --- a/common/src/main/java/dev/latvian/kubejs/client/asset/LangEventJS.java +++ b/common/src/main/java/dev/latvian/kubejs/client/asset/LangEventJS.java @@ -3,10 +3,12 @@ import dev.latvian.kubejs.KubeJS; import dev.latvian.kubejs.event.EventJS; import dev.latvian.kubejs.item.ItemStackJS; +import lombok.val; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; +import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; @@ -24,6 +26,7 @@ public LangEventJS() { namespace2lang2entries = new HashMap<>(); } + @NotNull public LangEntry get(String namespace, String lang) { if (namespace == null || lang == null || namespace.isEmpty() || lang.isEmpty() || !PATTERN.matcher(lang).matches()) { throw new IllegalArgumentException("Invalid namespace or lang: [" + namespace + ", " + lang + "]"); @@ -41,7 +44,7 @@ public void renameItem(String lang, ItemStackJS stack, String name) { if (stack == null || stack.isEmpty()) { return; } - var desc = stack.getItem().getDescriptionId(); + val desc = stack.getItem().getDescriptionId(); if (desc != null && !desc.isEmpty()) { get(stack.getMod(), lang).add(desc, name); } @@ -51,9 +54,9 @@ public void renameBlock(String lang, Block block, String name) { if (block == null || block == Blocks.AIR) { return; } - var desc = block.getDescriptionId(); + val desc = block.getDescriptionId(); if (desc != null && !desc.isEmpty()) { - var modid = Registry.BLOCK.getKey(block).getNamespace(); + val modid = Registry.BLOCK.getKey(block).getNamespace(); get(modid, lang).add(desc, name); } } diff --git a/common/src/main/java/dev/latvian/kubejs/client/error/KubeJSErrorScreen.java b/common/src/main/java/dev/latvian/kubejs/client/error/KubeJSErrorScreen.java new file mode 100644 index 000000000..286403c97 --- /dev/null +++ b/common/src/main/java/dev/latvian/kubejs/client/error/KubeJSErrorScreen.java @@ -0,0 +1,130 @@ +package dev.latvian.kubejs.client.error; + +import com.mojang.blaze3d.vertex.PoseStack; +import dev.latvian.kubejs.script.ScriptType; +import dev.latvian.kubejs.CommonProperties; +import lombok.val; +import net.minecraft.ChatFormatting; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.MultiLineLabel; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.*; +import net.minecraft.util.Mth; + +import java.util.List; +import java.util.Objects; + +public class KubeJSErrorScreen extends Screen { + public static boolean used = !CommonProperties.get().startupErrorGUI; + + public final ScriptType type; + private final Screen lastScreen; + private final boolean canClose; + private MultiLineLabel multilineMessage; + + public KubeJSErrorScreen(ScriptType type, Screen lastScreen, boolean canClose) { + super(new TextComponent("")); + this.type = type; + this.lastScreen = lastScreen; + this.canClose = canClose; + this.multilineMessage = MultiLineLabel.EMPTY; + } + + @Override + public String getNarrationMessage() { + return "There were KubeJS startup errors!"; + } + + @Override + protected void init() { + super.init(); + + val formatted = new TextComponent(""); + formatted.append( + new TextComponent("There were KubeJS startup errors ") + .append(new TextComponent("[" + type.errors.size() + "]").withStyle(ChatFormatting.DARK_RED)) + .append("!") + ); + + val style = Style.EMPTY.withColor(TextColor.fromRgb(0xD19893)); + + { + List errors = type.errors; + for (int i = 0, errorsSize = errors.size(); i < errorsSize; i++) { + formatted.append("\n") + .append( + new TextComponent((i + 1) + ") ").withStyle(ChatFormatting.DARK_RED) + .append( + new TextComponent(errors.get(i) + .replace("Error occurred while handling event ", "Error in ") + .replace("dev.latvian.mods.rhino.", "...rhino.") + .replace("dev.latvian.kubejs.", "...") + ) + .withStyle(style))); + } + } + + this.multilineMessage = MultiLineLabel.create(this.font, formatted, this.width - 12); + int i = this.height - 26; + + if (CommonProperties.get().startupErrorReportUrl.isBlank()) { + this.addButton(new Button(this.width / 2 - 155, i, 150, 20, new TextComponent("Open startup.log"), this::openLog)); + this.addButton(new Button(this.width / 2 - 155 + 160, i, 150, 20, new TextComponent("Back"), this::quit)); + } else { + this.addButton(new Button(this.width / 4 - 55, i, 100, 20, new TextComponent("Open startup.log"), this::openLog)); + this.addButton(new Button(this.width / 2 - 50, i, 100, 20, new TextComponent("Report"), this::report)); + this.addButton(new Button(this.width * 3 / 4 - 45, i, 100, 20, new TextComponent("Quit"), this::quit)); + } + } + + private void quit(Button button) { + used = true; + if (canClose) { + onClose(); + } else { + minecraft.stop(); + } + } + + private void report(Button button) { + handleComponentClicked(Style.EMPTY.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, CommonProperties.get().startupErrorReportUrl))); + } + + private void openLog(Button button) { + handleComponentClicked(Style.EMPTY.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, type.getLogFile().toAbsolutePath().toString()))); + } + + @Override + public void render(PoseStack stack, int i, int j, float f) { + this.renderBackground(stack); + this.multilineMessage.renderCentered(stack, this.width / 2, this.messageTop()); + super.render(stack, i, j, f); + } + + private int titleTop() { + int i = (this.height - this.messageHeight()) / 2; + int var10000 = i - 20; + Objects.requireNonNull(this.font); + return Mth.clamp(var10000 - 9, 10, 80); + } + + private int messageTop() { + return this.titleTop() + 20; + } + + private int messageHeight() { + int lineCount = this.multilineMessage.getLineCount(); + Objects.requireNonNull(this.font); + return lineCount * 9; + } + + @Override + public boolean shouldCloseOnEsc() { + return canClose; + } + + @Override + public void onClose() { + minecraft.setScreen(lastScreen); + } +} diff --git a/common/src/main/java/dev/latvian/kubejs/client/painter/Painter.java b/common/src/main/java/dev/latvian/kubejs/client/painter/Painter.java index 855d712c0..ebb3639f3 100644 --- a/common/src/main/java/dev/latvian/kubejs/client/painter/Painter.java +++ b/common/src/main/java/dev/latvian/kubejs/client/painter/Painter.java @@ -12,6 +12,7 @@ import dev.latvian.mods.rhino.util.unit.MutableUnit; import dev.latvian.mods.rhino.util.unit.Unit; import dev.latvian.mods.rhino.util.unit.UnitStorage; +import lombok.val; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; import net.minecraft.nbt.CompoundTag; @@ -122,7 +123,7 @@ public WorldPainterObject[] getWorldObjects() { } public void setVariable(String key, Unit variable) { - Unit original = unitStorage.getVariable(key); + val original = unitStorage.getVariable(key); if (original instanceof MutableUnit) { ((MutableUnit) original).set(variable.get()); @@ -134,7 +135,7 @@ public void setVariable(String key, Unit variable) { } public void inGameScreenDraw(PoseStack matrices, float delta) { - var mc = Minecraft.getInstance(); + val mc = Minecraft.getInstance(); if (mc.player == null || mc.options.renderDebug || mc.screen != null) { return; @@ -144,7 +145,7 @@ public void inGameScreenDraw(PoseStack matrices, float delta) { RenderSystem.enableDepthTest(); //RenderSystem.disableLighting(); - var event = new ScreenPaintEventJS(mc, matrices, delta); + val event = new ScreenPaintEventJS(mc, matrices, delta); deltaUnit.set(delta); screenWidthUnit.set(event.width); screenHeightUnit.set(event.height); @@ -153,13 +154,13 @@ public void inGameScreenDraw(PoseStack matrices, float delta) { mouseYUnit.set(event.height / 2F); event.post(KubeJSEvents.CLIENT_PAINT_SCREEN); - for (var object : getScreenObjects()) { + for (val object : getScreenObjects()) { if (object.visible && (object.draw == Painter.DRAW_ALWAYS || object.draw == Painter.DRAW_INGAME)) { object.preDraw(event); } } - for (var object : getScreenObjects()) { + for (val object : getScreenObjects()) { if (object.visible && (object.draw == Painter.DRAW_ALWAYS || object.draw == Painter.DRAW_INGAME)) { object.draw(event); } @@ -167,7 +168,7 @@ public void inGameScreenDraw(PoseStack matrices, float delta) { } public void guiScreenDraw(Screen screen, PoseStack matrices, int mouseX, int mouseY, float delta) { - var mc = Minecraft.getInstance(); + val mc = Minecraft.getInstance(); if (mc.player == null) { return; @@ -177,7 +178,7 @@ public void guiScreenDraw(Screen screen, PoseStack matrices, int mouseX, int mou RenderSystem.defaultBlendFunc(); //RenderSystem.disableLighting(); - var event = new ScreenPaintEventJS(mc, screen, matrices, mouseX, mouseY, delta); + val event = new ScreenPaintEventJS(mc, screen, matrices, mouseX, mouseY, delta); deltaUnit.set(delta); screenWidthUnit.set(event.width); screenHeightUnit.set(event.height); @@ -187,13 +188,13 @@ public void guiScreenDraw(Screen screen, PoseStack matrices, int mouseX, int mou // event.resetShaderColor(); event.post(KubeJSEvents.CLIENT_PAINT_SCREEN); - for (var object : getScreenObjects()) { + for (val object : getScreenObjects()) { if (object.visible && (object.draw == Painter.DRAW_ALWAYS || object.draw == Painter.DRAW_GUI)) { object.preDraw(event); } } - for (var object : getScreenObjects()) { + for (val object : getScreenObjects()) { if (object.visible && (object.draw == Painter.DRAW_ALWAYS || object.draw == Painter.DRAW_GUI)) { object.draw(event); } diff --git a/common/src/main/java/dev/latvian/kubejs/client/painter/screen/ItemObject.java b/common/src/main/java/dev/latvian/kubejs/client/painter/screen/ItemObject.java index 2b77f9433..cd02beb43 100644 --- a/common/src/main/java/dev/latvian/kubejs/client/painter/screen/ItemObject.java +++ b/common/src/main/java/dev/latvian/kubejs/client/painter/screen/ItemObject.java @@ -12,6 +12,7 @@ import dev.latvian.mods.rhino.util.unit.ConstantUnit; import dev.latvian.mods.rhino.util.unit.FixedUnit; import dev.latvian.mods.rhino.util.unit.Unit; +import lombok.val; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.block.model.ItemTransforms; @@ -56,11 +57,11 @@ public void draw(ScreenPaintEventJS event) { return; } - var aw = w.get(); - var ah = h.get(); - var ax = event.alignX(x.get(), aw, alignX); - var ay = event.alignY(y.get(), ah, alignY); - var az = z.get(); + val aw = w.get(); + val ah = h.get(); + val ax = event.alignX(x.get(), aw, alignX); + val ay = event.alignY(y.get(), ah, alignY); + val az = z.get(); event.push(); event.translate(ax, ay, az); @@ -79,9 +80,9 @@ public static void drawItem(PoseStack poseStack, ItemStack stack, int hash, bool return; } - var mc = Minecraft.getInstance(); - var itemRenderer = mc.getItemRenderer(); - var bakedModel = itemRenderer.getModel(stack, mc.player != null ? mc.player.level : null, mc.player); + val mc = Minecraft.getInstance(); + val itemRenderer = mc.getItemRenderer(); + val bakedModel = itemRenderer.getModel(stack, mc.player != null ? mc.player.level : null, mc.player); mc.getTextureManager().getTexture(InventoryMenu.BLOCK_ATLAS).setFilter(false, false); // RenderSystem.setShaderTexture(0, InventoryMenu.BLOCK_ATLAS); @@ -96,7 +97,7 @@ public static void drawItem(PoseStack poseStack, ItemStack stack, int hash, bool // modelViewStack.scale(16F, 16F, 16F); // RenderSystem.applyModelViewMatrix(); MultiBufferSource.BufferSource bufferSource = Minecraft.getInstance().renderBuffers().bufferSource(); - var flatLight = !bakedModel.usesBlockLight(); + val flatLight = !bakedModel.usesBlockLight(); if (flatLight) { Lighting.setupForFlatItems(); @@ -114,11 +115,11 @@ public static void drawItem(PoseStack poseStack, ItemStack stack, int hash, bool // RenderSystem.applyModelViewMatrix(); if (renderOverlay) { - var t = Tesselator.getInstance(); - var font = mc.font; + val t = Tesselator.getInstance(); + val font = mc.font; if (stack.getCount() != 1 || text != null) { - var s = text == null ? String.valueOf(stack.getCount()) : text; + val s = text == null ? String.valueOf(stack.getCount()) : text; poseStack.pushPose(); poseStack.translate(9D - font.width(s), 1D, 20D); font.drawInBatch(s, 0F, 0F, 0xFFFFFF, true, poseStack.last().pose(), bufferSource, false, 0, 0xF000F0); @@ -140,7 +141,7 @@ public static void drawItem(PoseStack poseStack, ItemStack stack, int hash, bool RenderSystem.enableDepthTest(); } - var cooldown = mc.player == null ? 0F : mc.player.getCooldowns().getCooldownPercent(stack.getItem(), mc.getFrameTime()); + val cooldown = mc.player == null ? 0F : mc.player.getCooldowns().getCooldownPercent(stack.getItem(), mc.getFrameTime()); if (cooldown > 0F) { RenderSystem.disableDepthTest(); @@ -160,8 +161,8 @@ private static void draw(PoseStack matrixStack, Tesselator t, int x, int y, int } // RenderSystem.setShader(GameRenderer::getPositionColorShader); - var m = matrixStack.last().pose(); - var renderer = t.getBuilder(); + val m = matrixStack.last().pose(); + val renderer = t.getBuilder(); renderer.begin(GL11.GL_QUADS, DefaultVertexFormat.POSITION_COLOR); renderer.vertex(m, x, y, 0).color(red, green, blue, alpha).endVertex(); renderer.vertex(m, x, y + height, 0).color(red, green, blue, alpha).endVertex(); diff --git a/common/src/main/java/dev/latvian/kubejs/command/ArgumentTypeWrapper.java b/common/src/main/java/dev/latvian/kubejs/command/ArgumentTypeWrapper.java index 4216da6a5..2e61fcf07 100644 --- a/common/src/main/java/dev/latvian/kubejs/command/ArgumentTypeWrapper.java +++ b/common/src/main/java/dev/latvian/kubejs/command/ArgumentTypeWrapper.java @@ -11,6 +11,7 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import dev.latvian.kubejs.util.ClassWrapper; import dev.latvian.kubejs.util.ConsoleJS; +import lombok.val; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.arguments.AngleArgument; import net.minecraft.commands.arguments.ColorArgument; @@ -121,7 +122,7 @@ public enum ArgumentTypeWrapper { private static Map> byNameCache; public static ClassWrapper byName(ResourceLocation name) { - var wrapper = getOrCacheByName().get(name); + val wrapper = getOrCacheByName().get(name); if (wrapper == null) { throw new IllegalStateException("No argument type found for " + name); } @@ -129,7 +130,7 @@ public static ClassWrapper byName(ResourceLocation name) { } public static void printAll() { - for (var argType : getOrCacheByName().entrySet()) { + for (val argType : getOrCacheByName().entrySet()) { ConsoleJS.SERVER.info("Argument type: " + argType.getKey() + " -> " + argType.getValue()); } } @@ -138,7 +139,7 @@ public static void printAll() { private static Map> getOrCacheByName() { if (byNameCache == null) { byNameCache = new HashMap<>(); - for (var argType : ArgumentTypes.BY_CLASS.entrySet()) { + for (val argType : ArgumentTypes.BY_CLASS.entrySet()) { byNameCache.putIfAbsent(argType.getValue().name, new ClassWrapper(argType.getKey())); } } diff --git a/common/src/main/java/dev/latvian/kubejs/core/MinecraftClientKJS.java b/common/src/main/java/dev/latvian/kubejs/core/MinecraftClientKJS.java index 77a435624..1a5f4246c 100644 --- a/common/src/main/java/dev/latvian/kubejs/core/MinecraftClientKJS.java +++ b/common/src/main/java/dev/latvian/kubejs/core/MinecraftClientKJS.java @@ -2,8 +2,7 @@ import com.mojang.blaze3d.platform.InputConstants; import dev.latvian.kubejs.client.ClientProperties; -import dev.latvian.kubejs.util.ConsoleJS; -import dev.latvian.mods.rhino.util.HideFromJS; +import lombok.val; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.Component; @@ -38,7 +37,7 @@ public interface MinecraftClientKJS { } default String kjs$getCurrentWorldName() { - var server = kjs$self().getCurrentServer(); + val server = kjs$self().getCurrentServer(); return server == null ? "Singleplayer" : server.name; } diff --git a/common/src/main/java/dev/latvian/kubejs/event/EventsJS.java b/common/src/main/java/dev/latvian/kubejs/event/EventsJS.java index 9b2518207..6af7a66c6 100644 --- a/common/src/main/java/dev/latvian/kubejs/event/EventsJS.java +++ b/common/src/main/java/dev/latvian/kubejs/event/EventsJS.java @@ -1,9 +1,9 @@ package dev.latvian.kubejs.event; import dev.latvian.kubejs.script.ScriptManager; +import dev.latvian.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.RhinoException; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; import lombok.val; import org.jetbrains.annotations.NotNull; @@ -24,17 +24,13 @@ public EventsJS(ScriptManager t) { map = new Object2ObjectOpenHashMap<>(); } - public void listen(String id, IEventHandler handler) { - id = id.replace("yeet", "remove"); - - var list = map.get(id); - if (list == null) { - list = new ObjectArrayList<>(); - map.put(id, list); - } - - list.add(handler); - } + public void listen(String id, IEventHandler handler) { + map.computeIfAbsent( + id.replace("yeet", "remove"), + UtilsJS::keyIgnoredArrayList + ) + .add(handler); + } @NotNull public List handlers(String id) { diff --git a/common/src/main/java/dev/latvian/kubejs/generator/AssetJsonGenerator.java b/common/src/main/java/dev/latvian/kubejs/generator/AssetJsonGenerator.java index d245dfc10..f5a32b4f3 100644 --- a/common/src/main/java/dev/latvian/kubejs/generator/AssetJsonGenerator.java +++ b/common/src/main/java/dev/latvian/kubejs/generator/AssetJsonGenerator.java @@ -1,43 +1,40 @@ package dev.latvian.kubejs.generator; -import com.google.gson.JsonElement; import dev.latvian.kubejs.client.ModelGenerator; import dev.latvian.kubejs.client.MultipartBlockStateGenerator; import dev.latvian.kubejs.client.VariantBlockStateGenerator; +import dev.latvian.kubejs.script.data.GeneratedData; import dev.latvian.kubejs.util.ConsoleJS; +import lombok.val; +import net.minecraft.Util; import net.minecraft.resources.ResourceLocation; import java.util.Map; import java.util.function.Consumer; public class AssetJsonGenerator extends JsonGenerator { - - public AssetJsonGenerator(Map m) { + public AssetJsonGenerator(Map m) { super(ConsoleJS.CLIENT, m); - } + } public void blockState(ResourceLocation id, Consumer consumer) { - VariantBlockStateGenerator gen = new VariantBlockStateGenerator(); - consumer.accept(gen); + val gen = Util.make(new VariantBlockStateGenerator(), consumer); json(new ResourceLocation(id.getNamespace(), "blockstates/" + id.getPath()), gen.toJson()); } public void multipartState(ResourceLocation id, Consumer consumer) { - MultipartBlockStateGenerator gen = new MultipartBlockStateGenerator(); - consumer.accept(gen); + val gen = Util.make(new MultipartBlockStateGenerator(), consumer); json(new ResourceLocation(id.getNamespace(), "blockstates/" + id.getPath()), gen.toJson()); } public void blockModel(ResourceLocation id, Consumer consumer) { - ModelGenerator gen = new ModelGenerator(); - consumer.accept(gen); + val gen = Util.make(new ModelGenerator(), consumer); json(new ResourceLocation(id.getNamespace(), "models/block/" + id.getPath()), gen.toJson()); } public void itemModel(ResourceLocation id, Consumer consumer) { - ModelGenerator gen = new ModelGenerator(); - consumer.accept(gen); - json(new ResourceLocation(id.getNamespace(), "models/item/" + id.getPath()), gen.toJson()); + val gen = Util.make(new ModelGenerator(), consumer); + json(asItemModelLocation(id), gen.toJson()); } public static ResourceLocation asItemModelLocation(ResourceLocation id) { diff --git a/common/src/main/java/dev/latvian/kubejs/generator/DataJsonGenerator.java b/common/src/main/java/dev/latvian/kubejs/generator/DataJsonGenerator.java index 63e2aea1b..59b8ff0e9 100644 --- a/common/src/main/java/dev/latvian/kubejs/generator/DataJsonGenerator.java +++ b/common/src/main/java/dev/latvian/kubejs/generator/DataJsonGenerator.java @@ -1,13 +1,13 @@ package dev.latvian.kubejs.generator; -import com.google.gson.JsonElement; +import dev.latvian.kubejs.script.data.GeneratedData; import dev.latvian.kubejs.util.ConsoleJS; import net.minecraft.resources.ResourceLocation; import java.util.Map; public class DataJsonGenerator extends JsonGenerator { - public DataJsonGenerator(Map m) { + public DataJsonGenerator(Map m) { super(ConsoleJS.SERVER, m); } } diff --git a/common/src/main/java/dev/latvian/kubejs/generator/JsonGenerator.java b/common/src/main/java/dev/latvian/kubejs/generator/JsonGenerator.java index 4ffd5b1f2..64046839f 100644 --- a/common/src/main/java/dev/latvian/kubejs/generator/JsonGenerator.java +++ b/common/src/main/java/dev/latvian/kubejs/generator/JsonGenerator.java @@ -1,25 +1,33 @@ package dev.latvian.kubejs.generator; import com.google.gson.JsonElement; -import dev.latvian.kubejs.server.ServerSettings; +import dev.latvian.kubejs.DevProperties; +import dev.latvian.kubejs.script.data.GeneratedData; import dev.latvian.kubejs.util.ConsoleJS; +import dev.latvian.kubejs.util.Lazy; import net.minecraft.resources.ResourceLocation; +import java.nio.charset.StandardCharsets; import java.util.Map; +import java.util.function.Supplier; public class JsonGenerator { private final ConsoleJS console; - private final Map map; + private final Map generated; - public JsonGenerator(ConsoleJS c, Map m) { - console = c; - map = m; + public JsonGenerator(ConsoleJS console, Map generated) { + this.console = console; + this.generated = generated; } - public void json(ResourceLocation id, JsonElement json) { - map.put(id, json); + public void add(ResourceLocation id, Supplier data) { + generated.put(id, new GeneratedData(id, Lazy.of(data))); + } + + public void json(ResourceLocation id, JsonElement json) { + add(new ResourceLocation(id.getNamespace(), id.getPath() + ".json"), () -> json.toString().getBytes(StandardCharsets.UTF_8)); - if (console.getDebugEnabled() || console == ConsoleJS.SERVER && ServerSettings.instance.dataPackOutput) { + if (console.getDebugEnabled() || console == ConsoleJS.SERVER && DevProperties.get().dataPackOutput) { console.info("Generated " + id + ": " + json); } } diff --git a/common/src/main/java/dev/latvian/kubejs/item/ItemBuilder.java b/common/src/main/java/dev/latvian/kubejs/item/ItemBuilder.java index 77801e117..d14a6638b 100644 --- a/common/src/main/java/dev/latvian/kubejs/item/ItemBuilder.java +++ b/common/src/main/java/dev/latvian/kubejs/item/ItemBuilder.java @@ -15,9 +15,9 @@ import dev.latvian.kubejs.registry.RegistryInfos; import dev.latvian.kubejs.registry.types.tab.KjsTabs; import dev.latvian.kubejs.util.ConsoleJS; -import dev.latvian.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.annotations.typing.JSInfo; import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; +import lombok.val; import me.shedaniel.architectury.registry.ToolType; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; @@ -304,7 +304,7 @@ public ItemBuilder tooltip(Component text) { } public ItemBuilder group(String groupId) { - var tab = KjsTabs.get(groupId); + val tab = KjsTabs.get(groupId); if (tab != null) { this.group = tab; } @@ -313,7 +313,7 @@ public ItemBuilder group(String groupId) { @JSInfo("Colorizes item's texture of the given index. Index is used when you have multiple layers, e.g. a crushed ore (of rock + ore).") public ItemBuilder color(int index, ItemTintFunction color) { - if (!(tint instanceof ItemTintFunction.Mapped mapped)) { + if (!(tint instanceof ItemTintFunction.Mapped)) { tint = new ItemTintFunction.Mapped(); } ((ItemTintFunction.Mapped) tint).map.put(index, color); @@ -403,7 +403,7 @@ public ItemBuilder fireResistant() { } public Item.Properties createItemProperties() { - var properties = new KubeJSItemProperties(this); + val properties = new KubeJSItemProperties(this); properties.tab(group); @@ -416,7 +416,7 @@ public Item.Properties createItemProperties() { properties.rarity(rarity.rarity); if (tools != null) { - for (var entry : tools.entrySet()) { + for (val entry : tools.entrySet()) { appendToolType(properties, entry.getKey(), entry.getValue()); } } diff --git a/common/src/main/java/dev/latvian/kubejs/item/ItemTintFunction.java b/common/src/main/java/dev/latvian/kubejs/item/ItemTintFunction.java index 35caee605..39b0db135 100644 --- a/common/src/main/java/dev/latvian/kubejs/item/ItemTintFunction.java +++ b/common/src/main/java/dev/latvian/kubejs/item/ItemTintFunction.java @@ -1,9 +1,7 @@ package dev.latvian.kubejs.item; -import com.github.bsideup.jabel.Desugar; import dev.latvian.kubejs.core.BlockKJS; import dev.latvian.mods.rhino.BaseFunction; -import dev.latvian.mods.rhino.Context; import dev.latvian.mods.rhino.NativeJavaObject; import dev.latvian.mods.rhino.Undefined; import dev.latvian.mods.rhino.mod.util.color.Color; @@ -11,6 +9,7 @@ import dev.latvian.mods.rhino.mod.wrapper.ColorWrapper; import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import lombok.val; import net.minecraft.client.color.item.ItemColor; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; @@ -28,7 +27,6 @@ default ItemColor asItemColor() { return (stack, index) -> getColor(stack, index).getArgbKJS(); } - @Desugar record Fixed(Color color) implements ItemTintFunction { @Override public Color getColor(ItemStack stack, int index) { @@ -41,15 +39,15 @@ class Mapped implements ItemTintFunction { @Override public Color getColor(ItemStack stack, int index) { - var f = map.get(index); + val f = map.get(index); return f == null ? null : f.getColor(stack, index); } } ItemTintFunction BLOCK = (stack, index) -> { if (stack.getItem() instanceof BlockItem block) { - var s = block.getBlock().defaultBlockState(); - var internal = ((BlockKJS) s.getBlock()).getBlockBuilderKJS(); + val s = block.getBlock().defaultBlockState(); + val internal = ((BlockKJS) s.getBlock()).getBlockBuilderKJS(); if (internal != null && internal.tint != null) { return internal.tint.getColor(s, null, null, index); @@ -62,7 +60,7 @@ public Color getColor(ItemStack stack, int index) { ItemTintFunction POTION = (stack, index) -> new SimpleColor(PotionUtils.getColor(stack)); ItemTintFunction MAP = (stack, index) -> new SimpleColor(MapItem.getColor(stack)); ItemTintFunction DISPLAY_COLOR_NBT = (stack, index) -> { - var tag = stack.getTagElement("display"); + val tag = stack.getTagElement("display"); if (tag != null && tag.contains("color", 99)) { return new SimpleColor(tag.getInt("color")); @@ -78,10 +76,10 @@ static ItemTintFunction of(Object o) { } else if (o instanceof ItemTintFunction f) { return f; } else if (o instanceof List list) { - var map = new Mapped(); + val map = new Mapped(); for (int i = 0; i < list.size(); i++) { - var f = of(list.get(i)); + val f = of(list.get(i)); if (f != null) { map.map.put(i, f); @@ -90,7 +88,7 @@ static ItemTintFunction of(Object o) { return map; } else if (o instanceof CharSequence) { - var fn = switch (o.toString()) { + val fn = switch (o.toString()) { case "block" -> BLOCK; case "potion" -> POTION; case "map" -> MAP; diff --git a/common/src/main/java/dev/latvian/kubejs/item/custom/ShearsItemBuilder.java b/common/src/main/java/dev/latvian/kubejs/item/custom/ShearsItemBuilder.java index 181b88287..cc5617545 100644 --- a/common/src/main/java/dev/latvian/kubejs/item/custom/ShearsItemBuilder.java +++ b/common/src/main/java/dev/latvian/kubejs/item/custom/ShearsItemBuilder.java @@ -1,6 +1,7 @@ package dev.latvian.kubejs.item.custom; import dev.latvian.kubejs.item.ItemBuilder; +import lombok.val; import me.shedaniel.architectury.platform.Platform; import net.minecraft.core.dispenser.ShearsDispenseItemBehavior; import net.minecraft.resources.ResourceLocation; @@ -36,7 +37,7 @@ public ShearsItemBuilder speedBaseline(float f) { @Override public Item createObject() { - var item = new ShearsItemKJS(this); + val item = new ShearsItemKJS(this); DispenserBlock.registerBehavior(item, new ShearsDispenseItemBehavior()); return item; } diff --git a/common/src/main/java/dev/latvian/kubejs/loot/BlockLootEventJS.java b/common/src/main/java/dev/latvian/kubejs/loot/BlockLootEventJS.java index d6062e53b..bdeab9ed4 100644 --- a/common/src/main/java/dev/latvian/kubejs/loot/BlockLootEventJS.java +++ b/common/src/main/java/dev/latvian/kubejs/loot/BlockLootEventJS.java @@ -2,7 +2,7 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import dev.latvian.kubejs.block.predicate.BlockStatePredicate; +import dev.latvian.kubejs.block.BlockStatePredicate; import dev.latvian.kubejs.util.ConsoleJS; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; diff --git a/common/src/main/java/dev/latvian/kubejs/mixin/common/MinecraftMixin.java b/common/src/main/java/dev/latvian/kubejs/mixin/common/MinecraftMixin.java index 7f66f51c5..4d13d120a 100644 --- a/common/src/main/java/dev/latvian/kubejs/mixin/common/MinecraftMixin.java +++ b/common/src/main/java/dev/latvian/kubejs/mixin/common/MinecraftMixin.java @@ -1,9 +1,12 @@ package dev.latvian.kubejs.mixin.common; +import dev.latvian.kubejs.KubeJS; import dev.latvian.kubejs.client.ClientProperties; import dev.latvian.kubejs.client.KubeJSClientResourcePack; import dev.latvian.kubejs.core.MinecraftClientKJS; +import lombok.val; import net.minecraft.client.Minecraft; +import net.minecraft.server.packs.FilePackResources; import net.minecraft.server.packs.PackResources; import net.minecraft.server.packs.repository.PackRepository; import org.spongepowered.asm.mixin.Mixin; @@ -12,6 +15,7 @@ import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import java.util.ArrayList; import java.util.List; /** @@ -20,19 +24,36 @@ @Mixin(Minecraft.class) public abstract class MinecraftMixin implements MinecraftClientKJS { - @Inject(method = "createTitle", at = @At("HEAD"), cancellable = true) - private void kjs$setWindowTitle(CallbackInfoReturnable ci) { - String s = ClientProperties.get().title; - if (!s.isEmpty()) { - ci.setReturnValue(s); - } - } + @Inject(method = "createTitle", at = @At("HEAD"), cancellable = true) + private void kjs$setWindowTitle(CallbackInfoReturnable ci) { + val title = ClientProperties.get().title; + if (!title.isEmpty()) { + ci.setReturnValue(title); + } + } - @Redirect( - method = {"reloadResourcePacks", ""}, - at = @At(value = "INVOKE", target = "Lnet/minecraft/server/packs/repository/PackRepository;openAllSelected()Ljava/util/List;") - ) - private List kjs$loadPacks(PackRepository repository) { - return KubeJSClientResourcePack.inject(repository.openAllSelected()); - } + @Redirect( + method = {"reloadResourcePacks", ""}, + at = @At(value = "INVOKE", target = "Lnet/minecraft/server/packs/repository/PackRepository;openAllSelected()Ljava/util/List;") + ) + private List kjs$loadPacks(PackRepository repository) { + val packs = repository.openAllSelected(); + // only add the resource pack if KubeJS has loaded to prevent crashes on mod loading errors + if (KubeJS.instance == null) { + return packs; + } + + val injected = new ArrayList(packs.size() + 1); + injected.addAll(packs); + //KubeJS injected resources should have lower priority then user resources packs, which means file pack + int injectPos = injected.size(); + for (int i = 0; i < injectPos; i++) { + if (injected.get(i) instanceof FilePackResources) { + injectPos = i; + break; + } + } + injected.add(injectPos, new KubeJSClientResourcePack()); + return injected; + } } \ No newline at end of file diff --git a/common/src/main/java/dev/latvian/kubejs/recipe/KubeJSRecipeEventHandler.java b/common/src/main/java/dev/latvian/kubejs/recipe/KubeJSRecipeEventHandler.java index 3d1563f90..75063d51f 100644 --- a/common/src/main/java/dev/latvian/kubejs/recipe/KubeJSRecipeEventHandler.java +++ b/common/src/main/java/dev/latvian/kubejs/recipe/KubeJSRecipeEventHandler.java @@ -21,7 +21,7 @@ public static void init() { } private static void registry() { - SHAPED = KubeJSRegistries.recipeSerializers().register(new ResourceLocation(KubeJS.MOD_ID, "shaped"), ShapedKubeJSRecipe.SerializerKJS::new); - SHAPELESS = KubeJSRegistries.recipeSerializers().register(new ResourceLocation(KubeJS.MOD_ID, "shapeless"), ShapelessKubeJSRecipe.SerializerKJS::new); + SHAPED = KubeJSRegistries.recipeSerializers().register(KubeJS.rl("shaped"), ShapedKubeJSRecipe.SerializerKJS::new); + SHAPELESS = KubeJSRegistries.recipeSerializers().register(KubeJS.rl("shapeless"), ShapelessKubeJSRecipe.SerializerKJS::new); } } diff --git a/common/src/main/java/dev/latvian/kubejs/registry/BuilderBase.java b/common/src/main/java/dev/latvian/kubejs/registry/BuilderBase.java index 5a2fc23a1..bfa7d36d6 100644 --- a/common/src/main/java/dev/latvian/kubejs/registry/BuilderBase.java +++ b/common/src/main/java/dev/latvian/kubejs/registry/BuilderBase.java @@ -6,6 +6,7 @@ import dev.latvian.kubejs.util.ConsoleJS; import dev.latvian.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.annotations.typing.JSInfo; +import lombok.val; import net.minecraft.Util; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; @@ -147,14 +148,7 @@ public T createTransformedObject() { @Override public String toString() { - var n = getClass().getName(); - int i = n.lastIndexOf('.'); - - if (i != -1) { - n = n.substring(i + 1); - } - - return n + "[" + id + "]"; + return getClass().getSimpleName() + "[" + id + "]"; } @Deprecated diff --git a/common/src/main/java/dev/latvian/kubejs/registry/BuilderType.java b/common/src/main/java/dev/latvian/kubejs/registry/BuilderType.java index 845c59591..22caa042b 100644 --- a/common/src/main/java/dev/latvian/kubejs/registry/BuilderType.java +++ b/common/src/main/java/dev/latvian/kubejs/registry/BuilderType.java @@ -1,11 +1,8 @@ package dev.latvian.kubejs.registry; -import com.github.bsideup.jabel.Desugar; - -@Desugar public record BuilderType( - String type, - Class> builderClass, - BuilderFactory factory + String type, + Class> builderClass, + BuilderFactory factory ) { } \ No newline at end of file diff --git a/common/src/main/java/dev/latvian/kubejs/registry/RegistryEventJS.java b/common/src/main/java/dev/latvian/kubejs/registry/RegistryEventJS.java index 3473dd55d..e7c19d7af 100644 --- a/common/src/main/java/dev/latvian/kubejs/registry/RegistryEventJS.java +++ b/common/src/main/java/dev/latvian/kubejs/registry/RegistryEventJS.java @@ -3,6 +3,7 @@ import dev.latvian.kubejs.KubeJS; import dev.latvian.kubejs.event.StartupEventJS; import dev.latvian.kubejs.util.UtilsJS; +import lombok.val; import java.util.ArrayList; import java.util.List; @@ -18,13 +19,13 @@ public RegistryEventJS(RegistryInfo r) { } public BuilderBase create(String id, String type) { - var t = registry.types.get(type); + val t = registry.types.get(type); if (t == null) { throw new IllegalArgumentException("Unknown type '" + type + "' for object '" + id + "'!"); } - var b = t.factory().createBuilder(UtilsJS.getMCID(KubeJS.appendModId(id))); + val b = t.factory().createBuilder(UtilsJS.getMCID(KubeJS.appendModId(id))); if (b == null) { throw new IllegalArgumentException("Unknown type '" + type + "' for object '" + id + "'!"); @@ -37,13 +38,13 @@ public BuilderBase create(String id, String type) { } public BuilderBase create(String id) { - var t = registry.getDefaultType(); + val t = registry.getDefaultType(); if (t == null) { throw new IllegalArgumentException("Registry for type '" + registry.key.location() + "' doesn't have any builders registered!"); } - var b = t.factory().createBuilder(UtilsJS.getMCID(KubeJS.appendModId(id))); + val b = t.factory().createBuilder(UtilsJS.getMCID(KubeJS.appendModId(id))); if (b == null) { throw new IllegalArgumentException("Unknown type '" + t.type() + "' for object '" + id + "'!"); @@ -64,9 +65,9 @@ public CustomBuilderObject createCustom(String id, Supplier object) { if (object == null) { throw new IllegalArgumentException("Tried to register a null object with id: " + id); } - var rl = UtilsJS.getMCID(KubeJS.appendModId(id)); + val rl = UtilsJS.getMCID(KubeJS.appendModId(id)); - var b = new CustomBuilderObject(rl, object, registry); + val b = new CustomBuilderObject(rl, object, registry); registry.addBuilder(b); created.add(b); return b; diff --git a/common/src/main/java/dev/latvian/kubejs/registry/types/mobeffects/BasicMobEffect.java b/common/src/main/java/dev/latvian/kubejs/registry/types/mobeffects/BasicMobEffect.java index 41bbba813..8e5a6b93c 100644 --- a/common/src/main/java/dev/latvian/kubejs/registry/types/mobeffects/BasicMobEffect.java +++ b/common/src/main/java/dev/latvian/kubejs/registry/types/mobeffects/BasicMobEffect.java @@ -2,11 +2,11 @@ import dev.latvian.kubejs.registry.RegistryInfos; import dev.latvian.kubejs.script.ScriptType; +import lombok.val; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.attributes.Attribute; -import net.minecraft.world.entity.ai.attributes.AttributeInstance; import net.minecraft.world.entity.ai.attributes.AttributeMap; import net.minecraft.world.entity.ai.attributes.AttributeModifier; import org.jetbrains.annotations.NotNull; @@ -55,10 +55,10 @@ public Map getAttributeModifiers() { @Override public void removeAttributeModifiers(LivingEntity livingEntity, AttributeMap attributeMap, int i) { this.applyAttributeModifications(); - for (Map.Entry entry : this.attributeMap.entrySet()) { - AttributeInstance attributeInstance = attributeMap.getInstance(entry.getKey()); - if (attributeInstance != null) { - attributeInstance.removeModifier(entry.getValue()); + for (val entry : this.attributeMap.entrySet()) { + val instance = attributeMap.getInstance(entry.getKey()); + if (instance != null) { + instance.removeModifier(entry.getValue()); } } } @@ -66,12 +66,12 @@ public void removeAttributeModifiers(LivingEntity livingEntity, AttributeMap att @Override public void addAttributeModifiers(LivingEntity livingEntity, AttributeMap attributeMap, int i) { this.applyAttributeModifications(); - for (var attributeAttributeModifierEntry : this.attributeMap.entrySet()) { - AttributeInstance attributeInstance = attributeMap.getInstance(attributeAttributeModifierEntry.getKey()); - if (attributeInstance != null) { - AttributeModifier attributeModifier = attributeAttributeModifierEntry.getValue(); - attributeInstance.removeModifier(attributeModifier); - attributeInstance.addPermanentModifier(new AttributeModifier(attributeModifier.getId(), this.getDescriptionId() + " " + i, this.getAttributeModifierValue(i, attributeModifier), attributeModifier.getOperation())); + for (val entry : this.attributeMap.entrySet()) { + val instance = attributeMap.getInstance(entry.getKey()); + if (instance != null) { + val modifier = entry.getValue(); + instance.removeModifier(modifier); + instance.addPermanentModifier(new AttributeModifier(modifier.getId(), this.getDescriptionId() + " " + i, this.getAttributeModifierValue(i, modifier), modifier.getOperation())); } } diff --git a/common/src/main/java/dev/latvian/kubejs/registry/types/tab/CreativeTabRegistryEventJS.java b/common/src/main/java/dev/latvian/kubejs/registry/types/tab/CreativeTabRegistryEventJS.java index 3575fdbf9..7df3959a6 100644 --- a/common/src/main/java/dev/latvian/kubejs/registry/types/tab/CreativeTabRegistryEventJS.java +++ b/common/src/main/java/dev/latvian/kubejs/registry/types/tab/CreativeTabRegistryEventJS.java @@ -5,6 +5,7 @@ import dev.latvian.kubejs.item.ItemStackJS; import dev.latvian.kubejs.util.ConsoleJS; import dev.latvian.mods.rhino.annotations.typing.JSInfo; +import lombok.val; import me.shedaniel.architectury.registry.CreativeTabs; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.CreativeModeTab; @@ -22,9 +23,9 @@ public class CreativeTabRegistryEventJS extends EventJS { vanilla id is valid, but will be denied here to prevent confusion """) public CreativeModeTab create(String id, Supplier icon) { - ResourceLocation fullId = null; + ResourceLocation fullId; try { - fullId = new ResourceLocation(KubeJS.MOD_ID, id); + fullId = KubeJS.rl(id); } catch (Exception e) { ConsoleJS.STARTUP.error(String.format("Tab id '%s' is not valid!", id), e); return null; @@ -35,7 +36,7 @@ public CreativeModeTab create(String id, Supplier icon) { return KjsTabs.get(id); } - var tab = CreativeTabs.create(fullId, () -> icon.get().getItemStack()); + val tab = CreativeTabs.create(fullId, () -> icon.get().getItemStack()); KjsTabs.put(id, tab); return tab; diff --git a/common/src/main/java/dev/latvian/kubejs/registry/types/tab/KjsTabs.java b/common/src/main/java/dev/latvian/kubejs/registry/types/tab/KjsTabs.java index db2d60a28..23e050669 100644 --- a/common/src/main/java/dev/latvian/kubejs/registry/types/tab/KjsTabs.java +++ b/common/src/main/java/dev/latvian/kubejs/registry/types/tab/KjsTabs.java @@ -1,7 +1,7 @@ package dev.latvian.kubejs.registry.types.tab; -import dev.latvian.kubejs.KubeJS; import dev.latvian.mods.rhino.annotations.typing.JSInfo; +import lombok.val; import net.minecraft.world.item.CreativeModeTab; import java.util.HashMap; @@ -16,7 +16,7 @@ public abstract class KjsTabs { private static final Map TABS = new HashMap<>(); static { - for (var tab : CreativeModeTab.TABS) { + for (val tab : CreativeModeTab.TABS) { TABS.put(tab.getRecipeFolderName(), tab); } } diff --git a/common/src/main/java/dev/latvian/kubejs/script/RegistryTypeWrapperFactory.java b/common/src/main/java/dev/latvian/kubejs/script/RegistryTypeWrapperFactory.java index 7a714dee3..55e78edeb 100644 --- a/common/src/main/java/dev/latvian/kubejs/script/RegistryTypeWrapperFactory.java +++ b/common/src/main/java/dev/latvian/kubejs/script/RegistryTypeWrapperFactory.java @@ -5,6 +5,7 @@ import dev.latvian.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.util.wrap.TypeWrapperFactory; import dev.latvian.mods.rhino.util.wrap.TypeWrappers; +import lombok.val; import me.shedaniel.architectury.registry.Registry; import java.util.ArrayList; @@ -14,7 +15,7 @@ public class RegistryTypeWrapperFactory implements TypeWrapperFactory { private static List> all; public static void register(TypeWrappers wrappers) { - for (var wrapperFactory : getAll()) { + for (val wrapperFactory : getAll()) { try { wrappers.register(wrapperFactory.type, UtilsJS.cast(wrapperFactory)); } catch (IllegalArgumentException ignored) { diff --git a/common/src/main/java/dev/latvian/kubejs/script/ScriptFileInfo.java b/common/src/main/java/dev/latvian/kubejs/script/ScriptFileInfo.java index f999dd2ab..d8d767b65 100644 --- a/common/src/main/java/dev/latvian/kubejs/script/ScriptFileInfo.java +++ b/common/src/main/java/dev/latvian/kubejs/script/ScriptFileInfo.java @@ -53,16 +53,15 @@ public Throwable preload(ScriptSource source) { while ((line = reader.readLine()) != null) { line = line.trim(); - if (line.startsWith("//")) { - String[] s = line.substring(2).split(":", 2); + if (!line.startsWith("//")) { + break; + } + String[] s = line.substring(2).split(":", 2); - if (s.length == 2) { - properties.put(s[0].trim().toLowerCase(), s[1].trim()); - } - } else { - break; - } - } + if (s.length == 2) { + properties.put(s[0].trim().toLowerCase(), s[1].trim()); + } + } priority = Integer.parseInt(getProperty("priority", "0")); ignored = getProperty("ignored", "false").equals("true"); diff --git a/common/src/main/java/dev/latvian/kubejs/script/ScriptManager.java b/common/src/main/java/dev/latvian/kubejs/script/ScriptManager.java index ac16c6c02..005ae0dd0 100644 --- a/common/src/main/java/dev/latvian/kubejs/script/ScriptManager.java +++ b/common/src/main/java/dev/latvian/kubejs/script/ScriptManager.java @@ -3,7 +3,6 @@ import dev.latvian.kubejs.CommonProperties; import dev.latvian.kubejs.KubeJS; import dev.latvian.kubejs.KubeJSEvents; -import dev.latvian.kubejs.KubeJSPlugin; import dev.latvian.kubejs.event.EventsJS; import dev.latvian.kubejs.event.PlatformEventHandler; import dev.latvian.kubejs.event.StartupEventJS; @@ -12,12 +11,9 @@ import dev.latvian.kubejs.util.UtilsJS; import dev.latvian.mods.rhino.*; import dev.latvian.mods.rhino.util.remapper.RemapperManager; -import dev.latvian.mods.rhino.util.wrap.TypeWrappers; +import lombok.val; import org.apache.commons.io.IOUtils; -import org.jetbrains.annotations.Nullable; -import java.io.InputStream; -import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; @@ -30,27 +26,26 @@ */ public class ScriptManager { - private static final ThreadLocal CURRENT_CONTEXT = new ThreadLocal<>(); - - public final ScriptType type; + public final ScriptType type; public final Path directory; public final String exampleScript; public final EventsJS events; public final Map packs; private final ClassFilter classFilter; + public boolean firstLoad; private Map> javaClassCache; public Context context; public ScriptableObject topScope; - public ScriptManager(ScriptType t, Path p, String e) { - type = t; - directory = p; - exampleScript = e; + public ScriptManager(ScriptType type, Path path, String examplePath) { + this.type = type; + directory = path; + exampleScript = examplePath; events = new EventsJS(this); packs = new LinkedHashMap<>(); firstLoad = true; - classFilter = KubeJSPlugins.createClassFilter(type); + classFilter = KubeJSPlugins.createClassFilter(this.type); } public void unload() { @@ -68,23 +63,25 @@ public void loadFromDirectory() { if (Files.notExists(directory)) { UtilsJS.tryIO(() -> Files.createDirectories(directory)); - try (InputStream in = KubeJS.class.getResourceAsStream(exampleScript); - OutputStream out = Files.newOutputStream(directory.resolve("script.js"))) { - out.write(IOUtils.toByteArray(in)); - } catch (Exception ex) { + try (val in = KubeJS.class.getResourceAsStream(exampleScript); + val out = Files.newOutputStream(directory.resolve("script.js"))) { + if (in != null) { + out.write(IOUtils.toByteArray(in)); + } + } catch (Exception ex) { ex.printStackTrace(); } } - ScriptPack pack = new ScriptPack(this, new ScriptPackInfo(directory.getFileName().toString(), "")); + val pack = new ScriptPack(this, new ScriptPackInfo(directory.getFileName().toString(), "")); KubeJS.loadScripts(pack, directory, ""); - for (ScriptFileInfo fileInfo : pack.info.scripts) { - ScriptSource.FromPath scriptSource = info -> directory.resolve(info.file); + for (val fileInfo : pack.info.scripts) { + val scriptSource = (ScriptSource.FromPath) info -> directory.resolve(info.file); - Throwable error = fileInfo.preload(scriptSource); + val error = fileInfo.preload(scriptSource); - String packMode = fileInfo.getPackMode(); + val packMode = fileInfo.getPackMode(); if (fileInfo.isIgnored() || (!packMode.equals("default") && !packMode.equals(CommonProperties.get().packMode))) { continue; } @@ -104,15 +101,9 @@ public boolean isClassAllowed(String name) { return classFilter.isAllowed(name); } - @Nullable - public static Context getCurrentContext() { - return CURRENT_CONTEXT.get(); - } - public void load() { //top level this.context = Context.enterWithNewFactory(); - CURRENT_CONTEXT.set(context); topScope = context.initStandardObjects(); //context related @@ -123,28 +114,28 @@ public void load() { context.setCustomProperty("type", type); //type wrapper / binding - TypeWrappers typeWrappers = context.getTypeWrappers(); - var bindingEvent = new BindingsEvent(this, context, topScope); + val typeWrappers = context.getTypeWrappers(); + val bindingEvent = new BindingsEvent(this, context, topScope); BindingsEvent.EVENT.invoker().accept(bindingEvent); - for (KubeJSPlugin plugin : KubeJSPlugins.all()) { + for (val plugin : KubeJSPlugins.all()) { plugin.addTypeWrappers(type, typeWrappers); plugin.addBindings(bindingEvent); } - long startAll = System.currentTimeMillis(); + val startAll = System.currentTimeMillis(); int loaded = 0; int total = 0; - for (ScriptPack pack : packs.values()) { + for (val pack : packs.values()) { try { pack.context = context; pack.scope = context.initStandardObjects(); pack.scope.setParentScope(topScope); - for (ScriptFile file : pack.scripts) { + for (val file : pack.scripts) { total++; - long start = System.currentTimeMillis(); + val start = System.currentTimeMillis(); if (file.load()) { loaded++; @@ -163,7 +154,13 @@ public void load() { } } - type.console.info("Loaded " + loaded + "/" + total + " KubeJS " + type.name + " scripts in " + (System.currentTimeMillis() - startAll) / 1000D + " s"); + type.console.infof( + "Loaded %d/%d KubeJS %s scripts in %s s", + loaded, + total, + type.name, + (System.currentTimeMillis() - startAll) / 1000D + ); Context.exit(); events.postToHandlers(KubeJSEvents.LOADED, events.handlers(KubeJSEvents.LOADED), new StartupEventJS()); @@ -176,7 +173,7 @@ public void load() { } public NativeJavaClass loadJavaClass(Scriptable scope, Object[] args) { - String name = args[0].toString(); + val name = args[0].toString(); if (name.isEmpty()) { throw Context.reportRuntimeError("Class name can't be empty!"); @@ -186,7 +183,7 @@ public NativeJavaClass loadJavaClass(Scriptable scope, Object[] args) { javaClassCache = new HashMap<>(); } - Optional ch = javaClassCache.get(name); + val ch = javaClassCache.get(name); if (ch == null) { javaClassCache.put(name, Optional.empty()); @@ -196,8 +193,8 @@ public NativeJavaClass loadJavaClass(Scriptable scope, Object[] args) { throw Context.reportRuntimeError("Class '" + name + "' is not allowed!"); } - Class c = Class.forName(name); - NativeJavaClass njc = new NativeJavaClass(scope, c); + val c = Class.forName(name); + val njc = new NativeJavaClass(scope, c); javaClassCache.put(name, Optional.of(njc)); return njc; } catch (Throwable ex) { diff --git a/common/src/main/java/dev/latvian/kubejs/script/ScriptType.java b/common/src/main/java/dev/latvian/kubejs/script/ScriptType.java index b2db94a6f..c54591a03 100644 --- a/common/src/main/java/dev/latvian/kubejs/script/ScriptType.java +++ b/common/src/main/java/dev/latvian/kubejs/script/ScriptType.java @@ -20,7 +20,7 @@ */ public enum ScriptType { STARTUP("startup", "KubeJS Startup", () -> KubeJS.startupScriptManager), - SERVER("server", "KubeJS Server", () -> ServerScriptManager.instance), + SERVER("server", "KubeJS Server", ServerScriptManager::scriptManager), CLIENT("client", "KubeJS Client", () -> KubeJS.clientScriptManager); static { diff --git a/common/src/main/java/dev/latvian/kubejs/script/data/ExportablePackResources.java b/common/src/main/java/dev/latvian/kubejs/script/data/ExportablePackResources.java new file mode 100644 index 000000000..eb8646e65 --- /dev/null +++ b/common/src/main/java/dev/latvian/kubejs/script/data/ExportablePackResources.java @@ -0,0 +1,13 @@ +package dev.latvian.kubejs.script.data; + +import net.minecraft.server.packs.PackResources; + +import java.io.IOException; +import java.nio.file.Path; + +public interface ExportablePackResources extends PackResources { + String METADATA_EXTENSION = ".mcmeta"; + String PACK_META = "pack" + METADATA_EXTENSION; + + void export(Path root) throws IOException; +} \ No newline at end of file diff --git a/common/src/main/java/dev/latvian/kubejs/script/data/GeneratedData.java b/common/src/main/java/dev/latvian/kubejs/script/data/GeneratedData.java new file mode 100644 index 000000000..412d0b366 --- /dev/null +++ b/common/src/main/java/dev/latvian/kubejs/script/data/GeneratedData.java @@ -0,0 +1,70 @@ +package dev.latvian.kubejs.script.data; + +import com.google.gson.JsonObject; +import lombok.val; +import dev.latvian.kubejs.KubeJS; +import dev.latvian.kubejs.util.Lazy; +import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.NotNull; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.function.Supplier; + +public record GeneratedData(ResourceLocation id, Lazy data) implements Supplier { + public static final GeneratedData INTERNAL_RELOAD = of( + KubeJS.id("__internal.reload"), + () -> new byte[0] + ); + + public static final GeneratedData PACK_META = of(KubeJS.id("pack.mcmeta"), () -> { + val json = new JsonObject(); + val pack = new JsonObject(); + pack.addProperty("description", "KubeJS Pack"); + pack.addProperty("pack_format", 15); + json.add("pack", pack); + return json.toString().getBytes(StandardCharsets.UTF_8); + }); + + public static final GeneratedData PACK_ICON = of(KubeJS.id("textures/kubejs_logo.png"), () -> { + try (val logoStream = GeneratedData.class.getResourceAsStream("/kubejs_logo.png")) { +// return Files.readAllBytes(Platform.getMod(KubeJS.MOD_ID).findResource("assets", "kubejs", "textures", "kubejs_logo.png").get()); + if (logoStream != null) { + return logoStream.readAllBytes(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return new byte[0]; + }); + + public static GeneratedData of(ResourceLocation id, Supplier data) { + return new GeneratedData(id, Lazy.of(data)); + } + + public static GeneratedData of(String namespace, String path, Supplier data) { + return new GeneratedData(new ResourceLocation(namespace, path), Lazy.of(data)); + } + + @Override + @NotNull + public InputStream get() { + return new ByteArrayInputStream(data.get()); + } + + @Override + public int hashCode() { + return id.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof GeneratedData g && id.equals(g.id); + } + + @Override + public String toString() { + return id.toString(); + } +} diff --git a/common/src/main/java/dev/latvian/kubejs/script/data/KubeJSResourcePack.java b/common/src/main/java/dev/latvian/kubejs/script/data/KubeJSResourcePack.java index 7ce88917d..88ca3c36c 100644 --- a/common/src/main/java/dev/latvian/kubejs/script/data/KubeJSResourcePack.java +++ b/common/src/main/java/dev/latvian/kubejs/script/data/KubeJSResourcePack.java @@ -1,203 +1,301 @@ package dev.latvian.kubejs.script.data; -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; -import com.google.gson.JsonElement; +import dev.latvian.kubejs.DevProperties; import dev.latvian.kubejs.KubeJS; import dev.latvian.kubejs.KubeJSPaths; -import dev.latvian.kubejs.registry.RegistryInfos; -import dev.latvian.kubejs.util.UtilsJS; +import dev.latvian.kubejs.util.ConsoleJS; import lombok.val; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.PackResources; +import net.minecraft.server.packs.AbstractPackResources; import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.ResourcePackFileNotFoundException; import net.minecraft.server.packs.metadata.MetadataSectionSerializer; import org.jetbrains.annotations.Nullable; -import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; +import java.util.*; import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; /** * @author LatvianModder */ -public abstract class KubeJSResourcePack implements PackResources { - private final PackType packType; - private Map cachedResources; - - public KubeJSResourcePack(PackType t) { - packType = t; - Objects.requireNonNull(KubeJS.instance, "KubeJS has not been initialized, this won't happen unless some OTHER mod failed to load first! Check your latest.log!"); - } - - private static String getFullPath(PackType type, ResourceLocation location) { - return String.format("%s/%s/%s", type.getDirectory(), location.getNamespace(), location.getPath()); - } - - @Override - @Environment(EnvType.CLIENT) - public InputStream getRootResource(String fileName) throws IOException { - if (fileName.equals("pack.png")) { - return KubeJSResourcePack.class.getResourceAsStream("/kubejs_logo.png"); - } - - throw new ResourcePackFileNotFoundException(KubeJSPaths.DIRECTORY.toFile(), fileName); - } - - @Override - public InputStream getResource(PackType type, ResourceLocation location) throws IOException { - String resourcePath = getFullPath(type, location); - - if (type != packType) { - throw new IllegalStateException(packType.getDirectory() + " KubeJS pack can't load " + resourcePath + "!"); - } - - Path file = KubeJSPaths.DIRECTORY.resolve(resourcePath); - - if (Files.exists(file)) { - return Files.newInputStream(file); - } else { - if (location.getPath().endsWith(".json")) { - JsonElement json = getCachedResources().get(location); - - if (json != null) { - return new ByteArrayInputStream(json.toString().getBytes(StandardCharsets.UTF_8)); - } - } - } - - throw new ResourcePackFileNotFoundException(KubeJSPaths.DIRECTORY.toFile(), resourcePath); - } - - @Override - public boolean hasResource(PackType type, ResourceLocation location) { - if (location.getPath().endsWith(".json")) { - JsonElement json = getCachedResources().get(location); - - if (json != null) { - return true; - } - } - - return type == packType && Files.exists(KubeJSPaths.DIRECTORY.resolve(getFullPath(type, location))); - } - - public Map getCachedResources() { - if (cachedResources == null) { - Map map = new HashMap<>(); - generateJsonFiles(map); - - cachedResources = new HashMap<>(); - - for (Map.Entry entry : map.entrySet()) { - cachedResources.put(new ResourceLocation(entry.getKey().getNamespace(), entry.getKey().getPath() + ".json"), entry.getValue()); - } - } - return cachedResources; - } - - public void generateJsonFiles(Map map) { - } - - @Override - public Collection getResources(PackType type, String namespace, String path, int maxDepth, Predicate filter) { - if (type != packType) { - return Collections.emptySet(); - } - - List list = Lists.newArrayList(); - - if (type == PackType.CLIENT_RESOURCES) { - if (path.equals("lang")) { - list.add(new ResourceLocation(KubeJS.MOD_ID, "lang/en_us.json")); - } - } else { - if (path.equals("loot_tables")) { - for (val id : RegistryInfos.BLOCK.objects.keySet()) { - list.add(new ResourceLocation(id.getNamespace(), "loot_tables/blocks/" + id.getPath() + ".json")); +public abstract class KubeJSResourcePack implements ExportablePackResources { + private final PackType packType; + private Map generated; + private Set generatedNamespaces; + + public KubeJSResourcePack(PackType type) { + packType = type; + } + + private static String getFullPath(PackType type, ResourceLocation location) { + return String.format("%s/%s/%s", type.getDirectory(), location.getNamespace(), location.getPath()); + } + + @Override + public InputStream getRootResource(String fileName) throws IOException { + return switch (fileName) { + case PACK_META -> GeneratedData.PACK_META.get(); + case "pack.png" -> GeneratedData.PACK_ICON.get(); + default -> throw new ResourcePackFileNotFoundException(KubeJSPaths.DIRECTORY.toFile(), fileName); + }; + } + + @Override + public InputStream getResource(PackType type, ResourceLocation location) throws IOException { + val generated = type == packType ? getGenerated().get(location) : null; + + if (generated == GeneratedData.INTERNAL_RELOAD) { + close(); + } + + if (generated != null) { + return generated.get(); + } + + throw new ResourcePackFileNotFoundException(KubeJSPaths.DIRECTORY.toFile(), getFullPath(type, location)); + } + + @Override + public boolean hasResource(PackType type, ResourceLocation location) { + return type == packType && getGenerated().get(location) != null; + } + + /** + * {@link GeneratedData#id()} -> {@link GeneratedData} + */ + public Map getGenerated() { + if (generated == null) { + generated = new HashMap<>(); + generate(generated); + + val debug = DevProperties.get().logGeneratedData || DevProperties.get().debugInfo; + + try { + val root = KubeJSPaths.get(packType); + + for (val dir : Files.list(root).filter(Files::isDirectory).toList()) { + val name = dir.getFileName().toString(); + + if (debug) { + KubeJS.LOGGER.info("# Walking namespace '{}'", name); + } + + for (val path : Files.walk(dir) + .filter(KubeJSResourcePack::filterPath) + .toList() + ) { + + val data = GeneratedData.of( + name, + dir.relativize(path).toString().replace('\\', '/').toLowerCase(), + () -> { + try { + return Files.readAllBytes(path); + } catch (Exception ex) { + ex.printStackTrace(); + return new byte[0]; + } + } + ); + + if (debug) { + KubeJS.LOGGER.info( + "- File found: '{}' ({} bytes)", + data.id(), + data.data().get().length + ); + } + + if (skipFile(data)) { + if (debug) { + KubeJS.LOGGER.info("- Skipping '{}'", data.id()); + } + continue; + } + + generated.put(data.id(), data); + } } - } - } - - UtilsJS.tryIO(() -> { - Path root = KubeJSPaths.get(type).toAbsolutePath(); - - if (Files.exists(root) && Files.isDirectory(root)) { - Path inputPath = root.getFileSystem().getPath(path); - - Files.walk(root) - .map(p -> root.relativize(p.toAbsolutePath())) - .filter(p -> p.getNameCount() > 1 && p.getNameCount() - 1 <= maxDepth) - .filter(p -> !p.toString().endsWith(".mcmeta")) - .filter(p -> p.subpath(1, p.getNameCount()).startsWith(inputPath)) - .filter(p -> filter.test(p.getFileName().toString())) - .map(p -> new ResourceLocation(p.getName(0).toString(), Joiner.on('/').join(p.subpath(1, Math.min(maxDepth, p.getNameCount()))))) - .forEach(list::add); - } - }); - - return list; - } - - @Override - public Set getNamespaces(PackType type) { - if (type != packType) { - return Collections.emptySet(); - } - - HashSet namespaces = new HashSet<>(); - namespaces.add("kubejs_generated"); - namespaces.add(KubeJS.MOD_ID); - - for (var builder : RegistryInfos.ALL_BUILDERS) { - namespaces.add(builder.id.getNamespace()); - } - - UtilsJS.tryIO(() -> - { - Path root = KubeJSPaths.get(type).toAbsolutePath(); - - if (Files.exists(root) && Files.isDirectory(root)) { - Files.walk(root, 1) - .map(path -> root.relativize(path.toAbsolutePath())) - .filter(path -> path.getNameCount() > 0) - .map(p -> p.toString().replaceAll("/$", "")) - .filter(s -> !s.isEmpty()) - .forEach(namespaces::add); - } - }); - - return namespaces; - } - - @Nullable - @Override - public T getMetadataSection(MetadataSectionSerializer serializer) { - return null; - } - - @Override - public String getName() { - return "KubeJS Resource Pack [" + packType.getDirectory() + "]"; - } - - @Override - public void close() { - cachedResources = null; - } + } catch (Exception ex) { + KubeJS.LOGGER.error( + "Failed to load files from kubejs/{}", + packType.getDirectory(), + ex + ); + } + + generated.put(GeneratedData.INTERNAL_RELOAD.id(), GeneratedData.INTERNAL_RELOAD); + + generated = Map.copyOf(generated); + + if (debug) { + KubeJS.LOGGER.info("Generated {} data ({} files)", packType, generated.size()); + } + } + + return generated; + } + + public void generate(Map map) { + } + + protected boolean skipFile(GeneratedData data) { + return false; + } + + @Override + public Collection getResources( + PackType type, + String namespace, + String path, + int maxDepth, + Predicate filter + ) { + if (type != packType) { + return Collections.emptySet(); + } + if (!path.endsWith("/")) { + path = path + "/"; + } + + val filtered = new ArrayList(); + + for (val generated : getGenerated().values()) { + val id = generated.id(); + + if (id.getNamespace().equals(namespace) + && id.getPath().startsWith(path) + && filter.test(id.getPath()) + ) { + filtered.add(id); + } + } + + return filtered; + } + + @Override + public Set getNamespaces(PackType type) { + if (type != packType) { + return Collections.emptySet(); + } + if (generatedNamespaces == null) { + generatedNamespaces = getGenerated() + .keySet() + .stream() + .map(ResourceLocation::getNamespace) + .collect(Collectors.toSet()); + } + + return generatedNamespaces; + } + + @Nullable + @Override + public T getMetadataSection(MetadataSectionSerializer serializer) throws IOException { + try (val in = this.getRootResource(PACK_META)) { + return AbstractPackResources.getMetadataFromStream(serializer, in); + } + } + + @Override + public String getName() { + return "KubeJS Resource Pack [" + packType.getDirectory() + "]"; + } + + @Override + public void close() { + generated = null; + generatedNamespaces = null; + } + + @Override + public void export(Path root) throws IOException { + for (val file : getGenerated().entrySet()) { + val path = root.resolve( + packType.getDirectory() + "/" + file.getKey().getNamespace() + "/" + file.getKey().getPath()); + Files.createDirectories(path.getParent()); + Files.write(path, file.getValue().data().get()); + } + + Files.write(root.resolve(PACK_META), GeneratedData.PACK_META.data().get()); + Files.write(root.resolve("pack.png"), GeneratedData.PACK_ICON.data().get()); + } + + public static Stream tryWalk(Path path) { + try { + return Files.walk(path); + } catch (Exception ignore) { + } + + return Stream.empty(); + } + + public static void scanForInvalidFiles(String pathName, Path path) throws IOException { + Files.list(path) + .filter(Files::isDirectory) + .flatMap(KubeJSResourcePack::tryWalk) + .filter(KubeJSResourcePack::filterPath) + .forEach(p -> { + try { + val fileName = p.getFileName().toString().toCharArray(); + + for (val c : fileName) { + if (c >= 'A' && c <= 'Z') { + val pathForLog = path.relativize(p) + .toString() + .replace('\\', '/'); + ConsoleJS.STARTUP.errorf("Invalid file name: Uppercase '%s' in %s%s", + c, + pathName, + pathForLog + ); + break; + } else if (!ResourceLocation.validPathChar(c)) { + val pathForLog = path.relativize(p) + .toString() + .replace('\\', '/'); + ConsoleJS.STARTUP.errorf("Invalid file name: Invalid character '%s' in %s%s", + c, + pathName, + pathForLog + ); + break; + } + } + } catch (Exception ex) { + val pathForLog = path.relativize(p) + .toString() + .replace('\\', '/'); + ConsoleJS.STARTUP.error("Invalid file name: %s%s".formatted(pathName, pathForLog)); + } + }); + } + + private static boolean filterPath(Path path) { + try { + if (!Files.isReadable(path) + || !Files.isRegularFile(path) + || Files.isHidden(path)) { + return false; + } + val name = path.getFileName().toString().toLowerCase(Locale.ROOT); + return !name.endsWith(".zip") + && !name.equals(".ds_store") + && !name.equals("thumbs.db") + && !name.equals("desktop.ini"); + } catch (IOException e) { + KubeJS.LOGGER.error( + "unable to determine whether file with path {} is valid, skipping", + path + ); + } + return false; + } } diff --git a/common/src/main/java/dev/latvian/kubejs/script/data/VirtualKubeJSDataPack.java b/common/src/main/java/dev/latvian/kubejs/script/data/VirtualKubeJSDataPack.java index fd1d28495..df5257b58 100644 --- a/common/src/main/java/dev/latvian/kubejs/script/data/VirtualKubeJSDataPack.java +++ b/common/src/main/java/dev/latvian/kubejs/script/data/VirtualKubeJSDataPack.java @@ -32,9 +32,9 @@ public class VirtualKubeJSDataPack extends AbstractPackResources { private final Map pathToData; private final Set namespaces; - public VirtualKubeJSDataPack(boolean h) { + public VirtualKubeJSDataPack(boolean highPriority) { super(new File("dummy")); - high = h; + high = highPriority; locationToData = new HashMap<>(); pathToData = new HashMap<>(); namespaces = new HashSet<>(); diff --git a/common/src/main/java/dev/latvian/kubejs/server/KubeJSServerEventHandler.java b/common/src/main/java/dev/latvian/kubejs/server/KubeJSServerEventHandler.java index fa8c28da3..475802511 100644 --- a/common/src/main/java/dev/latvian/kubejs/server/KubeJSServerEventHandler.java +++ b/common/src/main/java/dev/latvian/kubejs/server/KubeJSServerEventHandler.java @@ -74,6 +74,7 @@ public static void serverAboutToStart(MinecraftServer server) { public static void registerCommands(CommandDispatcher dispatcher, Commands.CommandSelection selection) { KubeJSCommands.register(dispatcher); + new CommandRegistryEventJS(dispatcher, selection).post(ScriptType.SERVER, KubeJSEvents.COMMAND_REGISTRY); } diff --git a/common/src/main/java/dev/latvian/kubejs/server/KubeJSServerResourcePack.java b/common/src/main/java/dev/latvian/kubejs/server/KubeJSServerResourcePack.java index 993f08076..64647e2b3 100644 --- a/common/src/main/java/dev/latvian/kubejs/server/KubeJSServerResourcePack.java +++ b/common/src/main/java/dev/latvian/kubejs/server/KubeJSServerResourcePack.java @@ -1,10 +1,11 @@ package dev.latvian.kubejs.server; -import com.google.gson.JsonElement; import dev.latvian.kubejs.generator.DataJsonGenerator; import dev.latvian.kubejs.registry.RegistryInfos; +import dev.latvian.kubejs.script.data.GeneratedData; import dev.latvian.kubejs.script.data.KubeJSResourcePack; import dev.latvian.kubejs.util.KubeJSPlugins; +import lombok.val; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.PackType; @@ -16,12 +17,13 @@ public KubeJSServerResourcePack() { } @Override - public void generateJsonFiles(Map map) { - DataJsonGenerator generator = new DataJsonGenerator(map); - KubeJSPlugins.forEachPlugin(p -> p.generateDataJsons(generator)); + public void generate(Map map) { + val generator = new DataJsonGenerator(map); - for (var builder : RegistryInfos.ALL_BUILDERS) { - builder.generateDataJsons(generator); - } + for (val builder : RegistryInfos.ALL_BUILDERS) { + builder.generateDataJsons(generator); + } + + KubeJSPlugins.forEachPlugin(p -> p.generateDataJsons(generator)); } } diff --git a/common/src/main/java/dev/latvian/kubejs/server/ServerScriptManager.java b/common/src/main/java/dev/latvian/kubejs/server/ServerScriptManager.java index c9b59d940..51beb4c69 100644 --- a/common/src/main/java/dev/latvian/kubejs/server/ServerScriptManager.java +++ b/common/src/main/java/dev/latvian/kubejs/server/ServerScriptManager.java @@ -20,7 +20,7 @@ import dev.latvian.kubejs.util.ConsoleJS; import dev.latvian.kubejs.util.KubeJSPlugins; import dev.latvian.kubejs.util.UtilsJS; -import dev.latvian.mods.rhino.annotations.typing.JSInfo; +import lombok.val; import me.shedaniel.architectury.platform.Platform; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.ServerResources; @@ -38,16 +38,20 @@ /** * @author LatvianModder */ -public class ServerScriptManager extends ScriptManager { +public class ServerScriptManager { public static ServerScriptManager instance; - @JSInfo("use `ServerScriptManager.instance` directly") - @Deprecated + public static ScriptManager scriptManager() { + if (instance == null) { + return null; + } + return instance.scriptManager; + } + public final ScriptManager scriptManager; public ServerScriptManager() { - super(ScriptType.SERVER, KubeJSPaths.SERVER_SCRIPTS, "/data/kubejs/example_server_script.js"); - scriptManager = this; + scriptManager = new ScriptManager(ScriptType.SERVER, KubeJSPaths.SERVER_SCRIPTS, "/data/kubejs/example_server_script.js"); } public void init(ServerResources serverResources) { @@ -62,24 +66,24 @@ public void init(ServerResources serverResources) { } public void reloadScriptManager(ResourceManager resourceManager) { - unload(); - loadFromDirectory(); + scriptManager.unload(); + scriptManager.loadFromDirectory(); Map> resPacks = new HashMap<>(); - for (var resource : resourceManager.listResources("kubejs", s -> s.endsWith(".js"))) { + for (val resource : resourceManager.listResources("kubejs", s -> s.endsWith(".js"))) { resPacks.computeIfAbsent(resource.getNamespace(), s -> new ArrayList<>()).add(resource); } - for (var entry : resPacks.entrySet()) { - var pack = new ScriptPack(this, new ScriptPackInfo(entry.getKey(), "kubejs/")); + for (val entry : resPacks.entrySet()) { + val pack = new ScriptPack(scriptManager, new ScriptPackInfo(entry.getKey(), "kubejs/")); - for (var id : entry.getValue()) { + for (val id : entry.getValue()) { pack.info.scripts.add(new ScriptFileInfo(pack.info, id.getPath().substring(7))); } - for (var fileInfo : pack.info.scripts) { - ScriptSource.FromResource scriptSource = info -> resourceManager.getResource(info.id); - Throwable error = fileInfo.preload(scriptSource); + for (val fileInfo : pack.info.scripts) { + val scriptSource = (ScriptSource.FromResource) info -> resourceManager.getResource(info.id); + val error = fileInfo.preload(scriptSource); if (fileInfo.isIgnored()) { continue; @@ -93,25 +97,26 @@ public void reloadScriptManager(ResourceManager resourceManager) { } pack.scripts.sort(null); - this.packs.put(pack.info.namespace, pack); + scriptManager.packs.put(pack.info.namespace, pack); } - load(); + scriptManager.load(); } public List resourcePackList(List original) { - var virtualDataPackLow = new VirtualKubeJSDataPack(false); - var virtualDataPackHigh = new VirtualKubeJSDataPack(true); - List list = new ArrayList<>(1 + original.size() + 10 + 1); + val virtualDataPackLow = new VirtualKubeJSDataPack(false); + val virtualDataPackHigh = new VirtualKubeJSDataPack(true); + + List list = new ArrayList<>(); //10 is expected kjs server resource size, obviously a little bit small list.add(virtualDataPackLow); list.addAll(original); list.add(new KubeJSServerResourcePack()); list.add(virtualDataPackHigh); - var resourceManager = new SimpleReloadableResourceManager(PackType.SERVER_DATA); + val resourceManager = new SimpleReloadableResourceManager(PackType.SERVER_DATA); - for (var resource : list) { + for (val resource : list) { resourceManager.add(resource); } diff --git a/common/src/main/java/dev/latvian/kubejs/server/TagEventJS.java b/common/src/main/java/dev/latvian/kubejs/server/TagEventJS.java index ca5471806..9091ab6c1 100644 --- a/common/src/main/java/dev/latvian/kubejs/server/TagEventJS.java +++ b/common/src/main/java/dev/latvian/kubejs/server/TagEventJS.java @@ -366,7 +366,7 @@ public void post(String event) { tags = new HashMap<>(); - for (var entry : map.entrySet()) { + for (val entry : map.entrySet()) { TagWrapper w = new TagWrapper<>(this, entry.getKey(), entry.getValue()); tags.put(entry.getKey(), w); ConsoleJS.SERVER.debug(type + "/#" + entry.getKey() + "; " + w.proxyList.size()); @@ -390,7 +390,7 @@ public void post(String event) { } else if (type.equals("blocks")) { for (val builderBase : RegistryInfos.BLOCK) { if (builderBase instanceof BlockBuilder builder) { - for (var s : builder.tags) { + for (val s : builder.tags) { add(s, builder.id); } } diff --git a/common/src/main/java/dev/latvian/kubejs/util/ClassWrapper.java b/common/src/main/java/dev/latvian/kubejs/util/ClassWrapper.java index dc3708e38..d8d684c05 100644 --- a/common/src/main/java/dev/latvian/kubejs/util/ClassWrapper.java +++ b/common/src/main/java/dev/latvian/kubejs/util/ClassWrapper.java @@ -1,6 +1,5 @@ package dev.latvian.kubejs.util; -import com.github.bsideup.jabel.Desugar; import dev.latvian.mods.rhino.NativeJavaClass; import dev.latvian.mods.rhino.Scriptable; import dev.latvian.mods.rhino.Context; @@ -9,7 +8,6 @@ /** * @author ZZZank */ -@Desugar public record ClassWrapper(Class wrappedClass) implements CustomJavaObjectWrapper { @Override public Scriptable wrapAsJavaObject(Context data, Scriptable scope, Class staticType) { diff --git a/common/src/main/java/dev/latvian/kubejs/util/ConsoleJS.java b/common/src/main/java/dev/latvian/kubejs/util/ConsoleJS.java index 35b8e7826..a4ac346ea 100644 --- a/common/src/main/java/dev/latvian/kubejs/util/ConsoleJS.java +++ b/common/src/main/java/dev/latvian/kubejs/util/ConsoleJS.java @@ -32,10 +32,6 @@ public class ConsoleJS { public static ConsoleJS SERVER; public static ConsoleJS CLIENT; - public static ConsoleJS byContext(Context cx) { - return (ConsoleJS) cx.getCustomProperty("console", STARTUP); - } - private static class StackTracePrintStream extends PrintStream { private final ConsoleJS console; private boolean first; diff --git a/common/src/main/java/dev/latvian/kubejs/util/KubeJSPlugins.java b/common/src/main/java/dev/latvian/kubejs/util/KubeJSPlugins.java index 3fd2d38cd..3cfdadc00 100644 --- a/common/src/main/java/dev/latvian/kubejs/util/KubeJSPlugins.java +++ b/common/src/main/java/dev/latvian/kubejs/util/KubeJSPlugins.java @@ -4,7 +4,7 @@ import dev.latvian.kubejs.KubeJSPlugin; import dev.latvian.kubejs.script.ScriptType; import lombok.val; -import me.shedaniel.architectury.platform.Platform; +import me.shedaniel.architectury.platform.Mod; import org.jetbrains.annotations.NotNull; import java.io.*; @@ -124,20 +124,15 @@ private static BufferedReader bufferedReaderFromStream(InputStream in) { return new BufferedReader(new InputStreamReader(new BufferedInputStream(in), StandardCharsets.UTF_8)); } - public static void initFromMods() { - val now = System.currentTimeMillis(); - KubeJS.LOGGER.info("Looking for KubeJS plugins..."); - - for (val mod : Platform.getMods()) { + public static void load(List mods) { + for (val mod : mods) { try { for (val path : mod.getFilePaths()) { load(mod.getModId(), path); } } catch (Exception ex) { - ex.printStackTrace(); + throw new RuntimeException("Failed to load KubeJS plugin for mod: " + mod, ex); } } - - KubeJS.LOGGER.info("Done in {} s", (System.currentTimeMillis() - now) / 1000L); } } diff --git a/common/src/main/java/dev/latvian/kubejs/util/Lazy.java b/common/src/main/java/dev/latvian/kubejs/util/Lazy.java index 44977d03b..50cd0d8cd 100644 --- a/common/src/main/java/dev/latvian/kubejs/util/Lazy.java +++ b/common/src/main/java/dev/latvian/kubejs/util/Lazy.java @@ -1,5 +1,7 @@ package dev.latvian.kubejs.util; +import lombok.val; + import java.util.ServiceLoader; import java.util.function.Supplier; @@ -14,7 +16,7 @@ public static Lazy of(Supplier supplier, long expiresInMs) { public static Lazy serviceLoader(Class type) { return of(() -> { - var loaded = ServiceLoader.load(type).iterator(); + val loaded = ServiceLoader.load(type).iterator(); if (loaded.hasNext()) { return loaded.next(); } diff --git a/common/src/main/java/dev/latvian/kubejs/util/UtilsJS.java b/common/src/main/java/dev/latvian/kubejs/util/UtilsJS.java index 9725fa894..46e64bfc0 100644 --- a/common/src/main/java/dev/latvian/kubejs/util/UtilsJS.java +++ b/common/src/main/java/dev/latvian/kubejs/util/UtilsJS.java @@ -55,6 +55,7 @@ import java.lang.reflect.WildcardType; import java.nio.file.Path; import java.util.*; +import java.util.function.Function; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -74,6 +75,10 @@ public class UtilsJS { public static final String[] EMPTY_STRING_ARRAY = new String[0]; public static final Predicate ALWAYS_TRUE = o -> true; + public static ArrayList keyIgnoredArrayList(K key) { + return new ArrayList<>(); + } + public interface TryIO { void run() throws IOException; } @@ -242,14 +247,14 @@ else if (o instanceof Map m) { return map; } // Lists, Collections, Iterables, GSON Arrays - else if (o instanceof Iterable itr) { + else if (o instanceof Iterable itr) { if (!type.checkList()) { return null; } - ListJS list = new ListJS(); + val list = new ListJS(); - for (Object o1 : itr) { + for (val o1 : itr) { list.add(o1); } @@ -273,9 +278,9 @@ else if (o instanceof JsonObject) { return null; } - MapJS map = new MapJS(((JsonObject) o).size()); + val map = new MapJS(((JsonObject) o).size()); - for (var entry : ((JsonObject) o).entrySet()) { + for (val entry : ((JsonObject) o).entrySet()) { map.put(entry.getKey(), entry.getValue()); } diff --git a/common/src/main/java/dev/latvian/kubejs/util/iter/EnumerateEntry.java b/common/src/main/java/dev/latvian/kubejs/util/iter/EnumerateEntry.java new file mode 100644 index 000000000..9a94a8157 --- /dev/null +++ b/common/src/main/java/dev/latvian/kubejs/util/iter/EnumerateEntry.java @@ -0,0 +1,7 @@ +package dev.latvian.kubejs.util.iter; + +/** + * @author ZZZank + */ +public record EnumerateEntry(int index, T value) { +} diff --git a/common/src/main/java/dev/latvian/kubejs/util/iter/EnumerateIterable.java b/common/src/main/java/dev/latvian/kubejs/util/iter/EnumerateIterable.java new file mode 100644 index 000000000..f93b7e798 --- /dev/null +++ b/common/src/main/java/dev/latvian/kubejs/util/iter/EnumerateIterable.java @@ -0,0 +1,22 @@ +package dev.latvian.kubejs.util.iter; + +import org.jetbrains.annotations.NotNull; + +import java.util.Iterator; +import java.util.Objects; + +/** + * @author ZZZank + */ +public class EnumerateIterable implements Iterable> { + private final Iterable inner; + + public EnumerateIterable(Iterable inner) { + this.inner = Objects.requireNonNull(inner); + } + + @Override + public @NotNull Iterator> iterator() { + return new EnumerateIterator<>(inner.iterator()); + } +} diff --git a/common/src/main/java/dev/latvian/kubejs/util/iter/EnumerateIterator.java b/common/src/main/java/dev/latvian/kubejs/util/iter/EnumerateIterator.java new file mode 100644 index 000000000..d4bbbecee --- /dev/null +++ b/common/src/main/java/dev/latvian/kubejs/util/iter/EnumerateIterator.java @@ -0,0 +1,31 @@ +package dev.latvian.kubejs.util.iter; + +import java.util.Iterator; +import java.util.Objects; + +/** + * @author ZZZank + */ +public class EnumerateIterator implements Iterator> { + private final Iterator inner; + private int index; + + public EnumerateIterator(Iterator inner) { + this.inner = Objects.requireNonNull(inner); + } + + @Override + public boolean hasNext() { + return inner.hasNext(); + } + + @Override + public EnumerateEntry next() { + return new EnumerateEntry<>(index++, inner.next()); + } + + @Override + public void remove() { + inner.remove(); + } +} diff --git a/common/src/main/java/dev/latvian/kubejs/world/gen/RemoveOresProperties.java b/common/src/main/java/dev/latvian/kubejs/world/gen/RemoveOresProperties.java index 352978322..0f681cb7f 100644 --- a/common/src/main/java/dev/latvian/kubejs/world/gen/RemoveOresProperties.java +++ b/common/src/main/java/dev/latvian/kubejs/world/gen/RemoveOresProperties.java @@ -1,6 +1,6 @@ package dev.latvian.kubejs.world.gen; -import dev.latvian.kubejs.block.predicate.BlockStatePredicate; +import dev.latvian.kubejs.block.BlockStatePredicate; import net.minecraft.world.level.levelgen.GenerationStep; /** diff --git a/fabric/build.gradle b/fabric/build.gradle index 557cbb45e..07791dc46 100644 --- a/fabric/build.gradle +++ b/fabric/build.gradle @@ -66,8 +66,8 @@ shadowJar { } remapJar { - input.set shadowJar.archiveFile - dependsOn shadowJar + setInput(shadeDowngradedApi.archiveFile) + dependsOn(shadowJar) archiveBaseName.set "${rootProject.archives_base_name}-${project.name}" archiveClassifier.set null } @@ -82,6 +82,8 @@ components.java { } } +assemble.dependsOn(downgradeJar, shadeDowngradedApi) + unifiedPublishing { project { releaseType = project.artifact_type diff --git a/fabric/src/main/java/dev/latvian/kubejs/integration/rei/REIPlugin.java b/fabric/src/main/java/dev/latvian/kubejs/integration/rei/REIPlugin.java index 79a0f534e..188441cbe 100644 --- a/fabric/src/main/java/dev/latvian/kubejs/integration/rei/REIPlugin.java +++ b/fabric/src/main/java/dev/latvian/kubejs/integration/rei/REIPlugin.java @@ -25,7 +25,7 @@ public class REIPlugin implements REIPluginV0 { @Override public ResourceLocation getPluginIdentifier() { - return new ResourceLocation(KubeJS.MOD_ID, "rei"); + return KubeJS.rl("rei"); } @Override diff --git a/forge/build.gradle b/forge/build.gradle index 408e48373..056494573 100644 --- a/forge/build.gradle +++ b/forge/build.gradle @@ -15,7 +15,7 @@ loom { forge { convertAccessWideners = true - extraAccessWideners.add loom.accessWidenerPath.get().asFile.name + extraAccessWideners.add(loom.accessWidenerPath.get().asFile.name) mixinConfig "kubejs-common.mixins.json" mixinConfig "kubejs.mixins.json" @@ -101,8 +101,8 @@ shadowJar { } remapJar { - input.set shadowJar.archiveFile - dependsOn shadowJar + setInput(shadeDowngradedApi.archiveFile) + dependsOn(shadowJar) archiveBaseName.set "${rootProject.archives_base_name}-${project.name}" archiveClassifier.set null } @@ -129,6 +129,8 @@ components.java { } } +assemble.dependsOn(downgradeJar, shadeDowngradedApi) + unifiedPublishing { project { releaseType = project.artifact_type diff --git a/gradle.properties b/gradle.properties index 6bbe9503a..d9bf153bb 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,8 @@ org.gradle.jvmargs=-Xmx3G org.gradle.daemon=false org.gradle.caching=true +jvmdowngrader_version=1.2.1 +parchment_version=1.16.5:2022.03.06 mod_id=kubejs archives_base_name=kubejs