diff --git a/.gitignore b/.gitignore index 4cc901d7b..872393485 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,10 @@ bin/ # fabric run/ + +# minecraft + +net/minecraft/ +!net/vulkanmod/ +*.log +*:Zone.Identifier \ No newline at end of file diff --git a/README.md b/README.md index 917d9bdb6..f26baa66f 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,10 @@ # VulkanMod -This is a fabric mod that introduces a brand new **Vulkan** based voxel rendering engine to **Minecraft java** in order to both replace the default OpenGL renderer and bring performance improvements. +This is a fabric mod that introduces a brand new **Vulkan** based voxel rendering engine to **Minecraft java** in order +to both replace the default OpenGL renderer and bring performance improvements. ### Why? + - Highly experimental project that overhauls and modernizes the internal renderer for Minecraft.
- Updates the renderer from OpenGL 3.2 to Vulkan 1.2.
- Provides a potential reference for a future-proof Vulkan codebase for Minecraft Java.
@@ -14,6 +16,7 @@ This is a fabric mod that introduces a brand new **Vulkan** based voxel renderin [![Demostration Video](http://img.youtube.com/vi/sbr7UxcAmOE/0.jpg)](https://youtu.be/sbr7UxcAmOE) ## FAQ + - Remember to check the [Wiki](https://github.com/xCollateral/VulkanMod/wiki) we wrote before asking for support! ## Installation @@ -27,11 +30,13 @@ This is a fabric mod that introduces a brand new **Vulkan** based voxel renderin - [![GitHub Downloads (all assets, all releases)](https://img.shields.io/github/downloads/xCollateral/VulkanMod/total?style=flat-square&logo=github&label=Github%20Downloads)](https://github.com/xCollateral/VulkanMod/releases) ### Install guide: ->1) Install the [fabric modloader](https://fabricmc.net). + +> 1) Install the [fabric modloader](https://fabricmc.net). >1) Download and put the `Vulkanmod.jar` file into `.minecraft/mods` >1) Enjoy ! ## Useful links + @@ -51,18 +56,19 @@ This is a fabric mod that introduces a brand new **Vulkan** based voxel renderin
Discord server
- ## Features ### Optimizations: ->- [x] Multiple chunk culling algorithms + +> - [x] Multiple chunk culling algorithms >- [x] Reduced CPU overhead >- [x] Improved GPU performance >- [x] Indirect Draw mode (reduces CPU overhead) >- [x] Chunk rendering optimizations ### New changes: ->- [x] Native Wayland support + +> - [x] Native Wayland support >- [x] GPU selector >- [x] Windowed fullscreen mode >- [x] Revamped graphic settings menu @@ -70,8 +76,10 @@ This is a fabric mod that introduces a brand new **Vulkan** based voxel renderin >- [ ] Shader support >- [ ] Removed Herobrine - ## Notes -- This mod is still in development, please report issues in the [issue tab](https://github.com/xCollateral/VulkanMod/issues) with logs attached! -- This mode isn't just "minecraft on vulkan" (e.g: [zink](https://docs.mesa3d.org/drivers/zink.html) ), it is a full rewrite of the minecraft renderer. + +- This mod is still in development, please report issues in + the [issue tab](https://github.com/xCollateral/VulkanMod/issues) with logs attached! +- This mode isn't just "minecraft on vulkan" (e.g: [zink](https://docs.mesa3d.org/drivers/zink.html) ), it is a full + rewrite of the minecraft renderer. diff --git a/build.gradle b/build.gradle index 3f9e6b94d..44bd25d99 100644 --- a/build.gradle +++ b/build.gradle @@ -1,111 +1,140 @@ -plugins { - id 'fabric-loom' version '1.9.2' - id 'maven-publish' -} - -version = project.mod_version -group = project.maven_group - -base { - archivesName = project.archives_base_name -} - -loom { - accessWidenerPath = file("src/main/resources/vulkanmod.accesswidener") -} - -dependencies { - // To change the versions see the gradle.properties file - minecraft "com.mojang:minecraft:${project.minecraft_version}" - mappings loom.officialMojangMappings() - modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" - - // Fabric API. This is technically optional, but you probably want it anyway. - modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" - - ext.includeModule = { name -> - var module = fabricApi.module(name, project.fabric_version) - modImplementation(module) - include(module) - } - - includeModule("fabric-api-base") - includeModule("fabric-resource-loader-v0") - includeModule("fabric-rendering-v1") - includeModule("fabric-renderer-api-v1") - includeModule("fabric-rendering-fluids-v1") - includeModule("fabric-rendering-data-attachment-v1") - includeModule("fabric-block-view-api-v2") -} - -project.ext.lwjglVersion = "3.3.3" -project.ext.jomlVersion = "1.10.4" -project.ext.winNatives = "natives-windows" -project.ext.linuxNatives = "natives-linux" -project.ext.macosNatives = "natives-macos" -project.ext.macosArmNatives = "natives-macos-arm64" - -dependencies { - include(implementation("org.lwjgl:lwjgl-vulkan:$lwjglVersion")) - - ext.includeNatives = { name -> - include(implementation("$name:$lwjglVersion")) - include(runtimeOnly("$name:$lwjglVersion:$winNatives")) - include(runtimeOnly("$name:$lwjglVersion:$linuxNatives")) - include(runtimeOnly("$name:$lwjglVersion:$macosNatives")) - include(runtimeOnly("$name:$lwjglVersion:$macosArmNatives")) - } - - includeNatives("org.lwjgl:lwjgl-vma") - includeNatives("org.lwjgl:lwjgl-shaderc") - - //MoltenVK - include(runtimeOnly("org.lwjgl:lwjgl-vulkan:$lwjglVersion:$macosNatives")) - include(runtimeOnly("org.lwjgl:lwjgl-vulkan:$lwjglVersion:$macosArmNatives")) -} - -processResources { - inputs.property "version", project.version - - filesMatching("fabric.mod.json") { - expand "version": project.version - } -} - -tasks.withType(JavaCompile).configureEach { - it.options.release = 21 -} - -java { - // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task - // if it is present. - // If you remove this line, sources will not be generated. - withSourcesJar() - - sourceCompatibility = JavaVersion.VERSION_21 - targetCompatibility = JavaVersion.VERSION_21 -} - -jar { - from("LICENSE") { - rename { "${it}_${project.base.archivesName.get()}"} - } -} - -// configure the maven publication -publishing { - publications { - create("mavenJava", MavenPublication) { - artifactId = project.archives_base_name - from components.java - } - } - - // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. - repositories { - // Add repositories to publish to here. - // Notice: This block does NOT have the same function as the block in the top level. - // The repositories here will be used for publishing your artifact, not for - // retrieving dependencies. - } -} +plugins { + id 'fabric-loom' version '1.11.8' + id 'maven-publish' +} + +version = project.mod_version +group = project.maven_group + +base { + archivesName = project.archives_base_name +} + +repositories { + mavenCentral() + maven { + name = "ParchmentMC" + url = "https://maven.parchmentmc.org" + content { + includeGroup("org.parchmentmc.data") + } + } + maven { + name = "LWJGL Snapshots" + url = "https://central.sonatype.com/repository/maven-snapshots" + } +} + +loom { + accessWidenerPath = file("src/main/resources/vulkanmod.accesswidener") +} + +configurations.configureEach { + resolutionStrategy { + force "org.lwjgl:lwjgl:3.4.0-SNAPSHOT" + force "org.lwjgl:lwjgl-glfw:3.4.0-SNAPSHOT" + force "org.lwjgl:lwjgl-jemalloc:3.4.0-SNAPSHOT" + force "org.lwjgl:lwjgl-openal:3.4.0-SNAPSHOT" + force "org.lwjgl:lwjgl-freetype:3.4.0-SNAPSHOT" + force "org.lwjgl:lwjgl-stb:3.4.0-SNAPSHOT" + } +} + +dependencies { + // To change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings loom.layered { + officialMojangMappings() + parchment("org.parchmentmc.data:parchment-${project.minecraft_version}:${project.parchment_version}@zip") + } + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + + // Fabric API. This is technically optional, but you probably want it anyway. + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + + ext.includeModule = { name -> + var module = fabricApi.module(name, project.fabric_version) + modImplementation(module) + include(module) + } + + includeModule("fabric-api-base") + includeModule("fabric-resource-loader-v0") + includeModule("fabric-rendering-v1") + includeModule("fabric-renderer-api-v1") + includeModule("fabric-rendering-fluids-v1") + includeModule("fabric-data-attachment-api-v1") + includeModule("fabric-block-view-api-v2") +} + +project.ext.lwjglVersion = "3.4.0-SNAPSHOT" +project.ext.jomlVersion = "1.10.8" +project.ext.winNatives = "natives-windows" +project.ext.linuxNatives = "natives-linux" +project.ext.macosNatives = "natives-macos" +project.ext.macosArmNatives = "natives-macos-arm64" + +dependencies { + include(implementation("org.lwjgl:lwjgl-vulkan:$lwjglVersion")) + + ext.includeNatives = { name -> + include(implementation("$name:$lwjglVersion")) + include(runtimeOnly("$name:$lwjglVersion:$winNatives")) + include(runtimeOnly("$name:$lwjglVersion:$linuxNatives")) + include(runtimeOnly("$name:$lwjglVersion:$macosNatives")) + include(runtimeOnly("$name:$lwjglVersion:$macosArmNatives")) + } + + includeNatives("org.lwjgl:lwjgl-vma") + includeNatives("org.lwjgl:lwjgl-shaderc") + + //MoltenVK + include(runtimeOnly("org.lwjgl:lwjgl-vulkan:$lwjglVersion:$macosNatives")) + include(runtimeOnly("org.lwjgl:lwjgl-vulkan:$lwjglVersion:$macosArmNatives")) +} + +processResources { + inputs.property "version", project.version + + filesMatching("fabric.mod.json") { + expand "version": project.version + } +} + +tasks.withType(JavaCompile).configureEach { + it.options.release = 25 +} + +java { + // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task + // if it is present. + // If you remove this line, sources will not be generated. + withSourcesJar() + + sourceCompatibility = JavaVersion.VERSION_25 + targetCompatibility = JavaVersion.VERSION_25 +} + +jar { + from("LICENSE") { + rename { "${it}_${project.base.archivesName.get()}" } + } +} + +// configure the maven publication +publishing { + publications { + create("mavenJava", MavenPublication) { + artifactId = project.archives_base_name + from components.java + } + } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { + // Add repositories to publish to here. + // Notice: This block does NOT have the same function as the block in the top level. + // The repositories here will be used for publishing your artifact, not for + // retrieving dependencies. + } +} diff --git a/gradle.properties b/gradle.properties index 017ec398f..40edd304a 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,17 +1,16 @@ # Done to increase the memory available to gradle. org.gradle.jvmargs=-Xmx3G org.gradle.parallel=true - # Fabric Properties # check these on https://fabricmc.net/develop -minecraft_version=1.21.1 -yarn_mappings=1.21.1+build.3 -loader_version=0.16.10 - +minecraft_version=1.21.10 +yarn_mappings=1.21.10+build.2 +loader_version=0.17.3 # Fabric API -fabric_version=0.114.0+1.21.1 - +fabric_version=0.136.0+1.21.10 # Mod Properties -mod_version = 0.5.4-dev -maven_group = net.vulkanmod -archives_base_name = VulkanMod_1.21.1 +mod_version=0.5.4-dev +maven_group=net.vulkanmod +archives_base_name=VulkanMod_1.21.10 +# Tooling +parchment_version=2025.10.12 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index cea7a793a..2e1113280 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/src/main/java/net/vulkanmod/Initializer.java b/src/main/java/net/vulkanmod/Initializer.java index ea9360265..225b62248 100644 --- a/src/main/java/net/vulkanmod/Initializer.java +++ b/src/main/java/net/vulkanmod/Initializer.java @@ -1,58 +1,47 @@ package net.vulkanmod; import net.fabricmc.api.ClientModInitializer; -import net.fabricmc.fabric.api.renderer.v1.RendererAccess; import net.fabricmc.loader.api.FabricLoader; import net.vulkanmod.config.Config; import net.vulkanmod.config.Platform; import net.vulkanmod.config.video.VideoModeManager; -import net.vulkanmod.render.chunk.build.frapi.VulkanModRenderer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.nio.file.Path; public class Initializer implements ClientModInitializer { - public static final Logger LOGGER = LogManager.getLogger("VulkanMod"); + public static final Logger LOGGER = LogManager.getLogger("VulkanMod"); + public static Config CONFIG; + private static String VERSION; - private static String VERSION; - public static Config CONFIG; + private static Config loadConfig(Path path) { + Config config = Config.load(path); - @Override - public void onInitializeClient() { + if (config == null) { + config = new Config(); + config.write(); + } - VERSION = FabricLoader.getInstance() - .getModContainer("vulkanmod") - .get() - .getMetadata() - .getVersion().getFriendlyString(); + return config; + } - LOGGER.info("== VulkanMod =="); + public static String getVersion() { + return VERSION; + } - Platform.init(); - VideoModeManager.init(); + @Override + public void onInitializeClient() { - var configPath = FabricLoader.getInstance() - .getConfigDir() - .resolve("vulkanmod_settings.json"); + VERSION = FabricLoader.getInstance().getModContainer("vulkanmod").get().getMetadata().getVersion().getFriendlyString(); - CONFIG = loadConfig(configPath); + LOGGER.info("== VulkanMod =="); - RendererAccess.INSTANCE.registerRenderer(VulkanModRenderer.INSTANCE); - } + Platform.init(); + VideoModeManager.init(); - private static Config loadConfig(Path path) { - Config config = Config.load(path); + var configPath = FabricLoader.getInstance().getConfigDir().resolve("vulkanmod_settings.json"); - if(config == null) { - config = new Config(); - config.write(); - } - - return config; - } - - public static String getVersion() { - return VERSION; - } + CONFIG = loadConfig(configPath); + } } diff --git a/src/main/java/net/vulkanmod/config/Config.java b/src/main/java/net/vulkanmod/config/Config.java index 05b4e7c62..0f93d3b46 100644 --- a/src/main/java/net/vulkanmod/config/Config.java +++ b/src/main/java/net/vulkanmod/config/Config.java @@ -13,25 +13,44 @@ import java.util.Collections; public class Config { + private static final Gson GSON = new GsonBuilder() + .setPrettyPrinting() + .excludeFieldsWithModifiers(Modifier.PRIVATE) + .create(); + private static Path CONFIG_PATH; public VideoModeSet.VideoMode videoMode = VideoModeManager.getFirstAvailable().getVideoMode(); public int windowMode = 0; - public int advCulling = 2; public boolean indirectDraw = true; - public boolean uniqueOpaqueLayer = true; public boolean entityCulling = true; public int device = -1; - public int ambientOcclusion = 1; public int frameQueueSize = 2; public int builderThreads = 0; - public boolean backFaceCulling = true; + public boolean enableRayTracing = false; + + public static Config load(Path path) { + Config config; + Config.CONFIG_PATH = path; + + if (Files.exists(path)) { + try (FileReader fileReader = new FileReader(path.toFile())) { + config = GSON.fromJson(fileReader, Config.class); + } catch (IOException exception) { + throw new RuntimeException(exception.getMessage()); + } + } else { + config = null; + } + + return config; + } public void write() { - if(!Files.exists(CONFIG_PATH.getParent())) { + if (!Files.exists(CONFIG_PATH.getParent())) { try { Files.createDirectories(CONFIG_PATH); } catch (IOException e) { @@ -45,30 +64,4 @@ public void write() { e.printStackTrace(); } } - - private static Path CONFIG_PATH; - - private static final Gson GSON = new GsonBuilder() - .setPrettyPrinting() - .excludeFieldsWithModifiers(Modifier.PRIVATE) - .create(); - - public static Config load(Path path) { - Config config; - Config.CONFIG_PATH = path; - - if (Files.exists(path)) { - try (FileReader fileReader = new FileReader(path.toFile())) { - config = GSON.fromJson(fileReader, Config.class); - } - catch (IOException exception) { - throw new RuntimeException(exception.getMessage()); - } - } - else { - config = null; - } - - return config; - } } diff --git a/src/main/java/net/vulkanmod/config/gui/GuiElement.java b/src/main/java/net/vulkanmod/config/gui/GuiElement.java index ee4305de1..763a8efc3 100644 --- a/src/main/java/net/vulkanmod/config/gui/GuiElement.java +++ b/src/main/java/net/vulkanmod/config/gui/GuiElement.java @@ -1,21 +1,20 @@ package net.vulkanmod.config.gui; import net.minecraft.Util; -import net.minecraft.client.gui.ComponentPath; import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.narration.NarratableEntry; import net.minecraft.client.gui.narration.NarrationElementOutput; -import net.minecraft.client.gui.navigation.FocusNavigationEvent; import net.minecraft.client.gui.navigation.ScreenRectangle; -import org.jetbrains.annotations.Nullable; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; public abstract class GuiElement implements GuiEventListener, NarratableEntry { - protected int width; - protected int height; public int x; public int y; - + protected int width; + protected int height; protected boolean hovered; protected long hoverStartTime; protected int hoverTime; @@ -75,57 +74,69 @@ public void updateState(double mX, double mY) { public float getHoverMultiplier(float time) { if (this.hovered) { return Math.min(((this.hoverTime) / time), 1.0f); - } - else { + } else { int delta = (int) (Util.getMillis() - this.hoverStopTime); return Math.max(1.0f - (delta / time), 0.0f); } } @Override - public void mouseMoved(double d, double e) { - GuiEventListener.super.mouseMoved(d, e); + public boolean mouseClicked(MouseButtonEvent mouseButtonEvent, boolean bl) { + return this.mouseClicked(mouseButtonEvent.x(), mouseButtonEvent.y(), mouseButtonEvent.button()); } - @Override - public boolean mouseClicked(double d, double e, int i) { - return GuiEventListener.super.mouseClicked(d, e, i); + public boolean mouseClicked(double mouseX, double mouseY, int button) { + return false; } @Override - public boolean mouseReleased(double d, double e, int i) { - return GuiEventListener.super.mouseReleased(d, e, i); + public boolean mouseReleased(MouseButtonEvent mouseButtonEvent) { + return this.mouseReleased(mouseButtonEvent.x(), mouseButtonEvent.y(), mouseButtonEvent.button()); + } + + public boolean mouseReleased(double mouseX, double mouseY, int button) { + return false; } @Override - public boolean mouseDragged(double d, double e, int i, double f, double g) { - return GuiEventListener.super.mouseDragged(d, e, i, f, g); + public boolean mouseDragged(MouseButtonEvent mouseButtonEvent, double dragX, double dragY) { + return this.mouseDragged(mouseButtonEvent.x(), mouseButtonEvent.y(), mouseButtonEvent.button(), dragX, dragY); + } + + public boolean mouseDragged(double mouseX, double mouseY, int button, double dragX, double dragY) { + return false; } @Override public boolean mouseScrolled(double d, double e, double f, double g) { - return GuiEventListener.super.mouseScrolled(d, e, f, g); + return false; } @Override - public boolean keyPressed(int i, int j, int k) { - return GuiEventListener.super.keyPressed(i, j, k); + public boolean keyPressed(KeyEvent keyEvent) { + return this.keyPressed(keyEvent.key(), keyEvent.scancode(), keyEvent.modifiers()); } - @Override - public boolean keyReleased(int i, int j, int k) { - return GuiEventListener.super.keyReleased(i, j, k); + public boolean keyPressed(int keyCode, int scanCode, int modifiers) { + return false; } @Override - public boolean charTyped(char c, int i) { - return GuiEventListener.super.charTyped(c, i); + public boolean keyReleased(KeyEvent keyEvent) { + return this.keyReleased(keyEvent.key(), keyEvent.scancode(), keyEvent.modifiers()); + } + + public boolean keyReleased(int keyCode, int scanCode, int modifiers) { + return false; } - @Nullable @Override - public ComponentPath nextFocusPath(FocusNavigationEvent focusNavigationEvent) { - return GuiEventListener.super.nextFocusPath(focusNavigationEvent); + public boolean charTyped(CharacterEvent characterEvent) { + return this.charTyped((char) characterEvent.codepoint(), characterEvent.modifiers()); + } + + public boolean charTyped(char codePoint, int modifiers) { + return false; } @Override @@ -134,11 +145,6 @@ public boolean isMouseOver(double mouseX, double mouseY) { && mouseX <= (this.x + this.width) && mouseY <= (this.y + this.height); } - @Nullable - @Override - public ComponentPath getCurrentFocusPath() { - return GuiEventListener.super.getCurrentFocusPath(); - } @Override public ScreenRectangle getRectangle() { @@ -146,13 +152,13 @@ public ScreenRectangle getRectangle() { } @Override - public void setFocused(boolean bl) { - + public boolean isFocused() { + return false; } @Override - public boolean isFocused() { - return false; + public void setFocused(boolean bl) { + } @Override diff --git a/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java b/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java index b4b3216c1..6cedcc61d 100644 --- a/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java +++ b/src/main/java/net/vulkanmod/config/gui/GuiRenderer.java @@ -1,15 +1,13 @@ package net.vulkanmod.config.gui; import com.mojang.blaze3d.platform.Window; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.*; +import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.renderer.GameRenderer; import net.minecraft.network.chat.Component; -import net.minecraft.util.FastColor; import net.minecraft.util.FormattedCharSequence; +import net.vulkanmod.vulkan.Renderer; import org.joml.Matrix4f; import java.util.List; @@ -19,18 +17,18 @@ public abstract class GuiRenderer { public static Minecraft minecraft; public static Font font; public static GuiGraphics guiGraphics; - public static PoseStack pose; - public static BufferBuilder bufferBuilder; - - private static boolean batching = false; - private static boolean drawing = false; + public static Matrix4f poseMatrix = new Matrix4f(); public static void setPoseStack(PoseStack poseStack) { - pose = poseStack; + poseMatrix = new Matrix4f(poseStack.last().pose()); + } + + public static void setPoseStack(Matrix4f matrix) { + poseMatrix = new Matrix4f(matrix); } public static void disableScissor() { - RenderSystem.disableScissor(); + Renderer.resetScissor(); } public static void enableScissor(int x, int y, int width, int height) { @@ -41,7 +39,7 @@ public static void enableScissor(int x, int y, int width, int height) { int yScaled = (int) (wHeight - (y + height) * scale); int widthScaled = (int) (width * scale); int heightScaled = (int) (height * scale); - RenderSystem.enableScissor(xScaled, yScaled, Math.max(0, widthScaled), Math.max(0, heightScaled)); + Renderer.setScissor(xScaled, yScaled, Math.max(0, widthScaled), Math.max(0, heightScaled)); } public static void fillBox(float x0, float y0, float width, float height, int color) { @@ -53,23 +51,7 @@ public static void fill(float x0, float y0, float x1, float y1, int color) { } public static void fill(float x0, float y0, float x1, float y1, float z, int color) { - Matrix4f matrix4f = pose.last().pose(); - - float a = (float) FastColor.ARGB32.alpha(color) / 255.0F; - float r = (float) FastColor.ARGB32.red(color) / 255.0F; - float g = (float) FastColor.ARGB32.green(color) / 255.0F; - float b = (float) FastColor.ARGB32.blue(color) / 255.0F; - - RenderSystem.setShader(GameRenderer::getPositionColorShader); - - setupBufferBuilder(); - - bufferBuilder.addVertex(matrix4f, x0, y0, z).setColor(r, g, b, a); - bufferBuilder.addVertex(matrix4f, x0, y1, z).setColor(r, g, b, a); - bufferBuilder.addVertex(matrix4f, x1, y1, z).setColor(r, g, b, a); - bufferBuilder.addVertex(matrix4f, x1, y0, z).setColor(r, g, b, a); - - submitIfNeeded(); + guiGraphics.fill((int) x0, (int) y0, (int) x1, (int) y1, color); } public static void fillGradient(float x0, float y0, float x1, float y1, int color1, int color2) { @@ -77,25 +59,7 @@ public static void fillGradient(float x0, float y0, float x1, float y1, int colo } public static void fillGradient(float x0, float y0, float x1, float y1, float z, int color1, int color2) { - float a1 = (float) FastColor.ARGB32.alpha(color1) / 255.0F; - float r1 = (float) FastColor.ARGB32.red(color1) / 255.0F; - float g1 = (float) FastColor.ARGB32.green(color1) / 255.0F; - float b1 = (float) FastColor.ARGB32.blue(color1) / 255.0F; - float a2 = (float) FastColor.ARGB32.alpha(color2) / 255.0F; - float r2 = (float) FastColor.ARGB32.red(color2) / 255.0F; - float g2 = (float) FastColor.ARGB32.green(color2) / 255.0F; - float b2 = (float) FastColor.ARGB32.blue(color2) / 255.0F; - - Matrix4f matrix4f = pose.last().pose(); - - setupBufferBuilder(); - - bufferBuilder.addVertex(matrix4f, x0, y0, z).setColor(r1, g1, b1, a1); - bufferBuilder.addVertex(matrix4f, x0, y1, z).setColor(r2, g2, b2, a2); - bufferBuilder.addVertex(matrix4f, x1, y1, z).setColor(r2, g2, b2, a2); - bufferBuilder.addVertex(matrix4f, x1, y0, z).setColor(r1, g1, b1, a1); - - submitIfNeeded(); + guiGraphics.fillGradient((int) x0, (int) y0, (int) x1, (int) y1, color1, color2); } public static void renderBoxBorder(float x0, float y0, float width, float height, float borderWidth, int color) { @@ -143,42 +107,11 @@ public static int getMaxTextWidth(Font font, List list) { } public static void beginBatch() { - batching = true; } public static void endBatch() { - RenderSystem.setShader(GameRenderer::getPositionColorShader); - MeshData meshData = bufferBuilder.build(); - - if (meshData != null) { - BufferUploader.drawWithShader(meshData); - meshData.close(); - } - - batching = false; - drawing = false; } public static void flush() { - guiGraphics.flush(); - - if (batching) { - endBatch(); - } - } - - private static void setupBufferBuilder() { - if (!batching || !drawing) { - bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); - drawing = true; - } - } - - private static void submitIfNeeded() { - if (!batching) { - RenderSystem.setShader(GameRenderer::getPositionColorShader); - BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); - drawing = false; - } } } diff --git a/src/main/java/net/vulkanmod/config/gui/OptionBlock.java b/src/main/java/net/vulkanmod/config/gui/OptionBlock.java index 6a6b31079..2225cc835 100644 --- a/src/main/java/net/vulkanmod/config/gui/OptionBlock.java +++ b/src/main/java/net/vulkanmod/config/gui/OptionBlock.java @@ -4,4 +4,4 @@ public record OptionBlock(String title, Option[] options) { -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/config/gui/VOptionList.java b/src/main/java/net/vulkanmod/config/gui/VOptionList.java index e814f5cc6..713d8f1af 100644 --- a/src/main/java/net/vulkanmod/config/gui/VOptionList.java +++ b/src/main/java/net/vulkanmod/config/gui/VOptionList.java @@ -1,13 +1,12 @@ package net.vulkanmod.config.gui; -import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.client.gui.components.events.GuiEventListener; -import net.minecraft.client.renderer.GameRenderer; import net.minecraft.util.Mth; import net.vulkanmod.config.gui.widget.OptionWidget; import net.vulkanmod.config.gui.widget.VAbstractWidget; import net.vulkanmod.config.option.Option; +import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.util.ColorUtil; import org.jetbrains.annotations.Nullable; @@ -139,8 +138,8 @@ public boolean mouseDragged(double mouseX, double mouseY, int button, double del return false; } - if (this.getFocused() != null) { - return this.getFocused().mouseDragged(mouseX, mouseY, button, deltaX, deltaY); + if (this.focused != null) { + return this.focused.mouseDragged(mouseX, mouseY, button, deltaX, deltaY); } if (!this.scrolling) { @@ -203,7 +202,7 @@ public void updateState(double mX, double mY) { } public void renderWidget(int mouseX, int mouseY) { - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); + VRenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); GuiRenderer.enableScissor(x, y, width, height); this.renderList(mouseX, mouseY); @@ -213,8 +212,7 @@ public void renderWidget(int mouseX, int mouseY) { // Scroll bar int maxScroll = this.getMaxScroll(); if (maxScroll > 0) { - RenderSystem.enableBlend(); - RenderSystem.setShader(GameRenderer::getPositionColorShader); + VRenderSystem.enableBlend(); int height = this.getHeight(); int totalLength = this.getTotalLength(); diff --git a/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java b/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java index 1a6d255b3..66a446ef2 100644 --- a/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java +++ b/src/main/java/net/vulkanmod/config/gui/VOptionScreen.java @@ -1,11 +1,11 @@ package net.vulkanmod.config.gui; import com.google.common.collect.Lists; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.Util; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; @@ -15,6 +15,7 @@ import net.vulkanmod.config.gui.widget.VButtonWidget; import net.vulkanmod.config.option.OptionPage; import net.vulkanmod.config.option.Options; +import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.util.ColorUtil; import java.util.ArrayList; @@ -27,21 +28,16 @@ public class VOptionScreen extends Screen { private final Screen parent; private final List optionPages; - + private final List pageButtons = Lists.newArrayList(); + private final List buttons = Lists.newArrayList(); private int currentListIdx = 0; - private int tooltipX; private int tooltipY; private int tooltipWidth; - private VButtonWidget supportButton; - private VButtonWidget doneButton; private VButtonWidget applyButton; - private final List pageButtons = Lists.newArrayList(); - private final List buttons = Lists.newArrayList(); - public VOptionScreen(Component title, Screen parent) { super(title); this.parent = parent; @@ -195,11 +191,12 @@ private void addButtons() { this.addWidget(this.supportButton); } - public boolean mouseClicked(double mouseX, double mouseY, int button) { + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean canFocus) { for (GuiEventListener element : this.children()) { - if (element.mouseClicked(mouseX, mouseY, button)) { + if (element.mouseClicked(event, canFocus)) { this.setFocused(element); - if (button == 0) { + if (event.button() == 0) { this.setDragging(true); } @@ -212,11 +209,11 @@ public boolean mouseClicked(double mouseX, double mouseY, int button) { } @Override - public boolean mouseReleased(double mouseX, double mouseY, int button) { + public boolean mouseReleased(MouseButtonEvent event) { this.setDragging(false); this.updateState(); - return this.getChildAt(mouseX, mouseY) - .filter(guiEventListener -> guiEventListener.mouseReleased(mouseX, mouseY, button)) + return this.getChildAt(event.x(), event.y()) + .filter(guiEventListener -> guiEventListener.mouseReleased(event)) .isPresent(); } @@ -231,7 +228,7 @@ public void renderBackground(GuiGraphics guiGraphics, int i, int j, float f) { this.renderPanorama(guiGraphics, f); } - this.renderBlurredBackground(f); + this.renderBlurredBackground(guiGraphics); this.renderMenuBackground(guiGraphics); } @@ -241,13 +238,12 @@ public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float delta) this.renderBackground(guiGraphics, 0, 0, delta); GuiRenderer.guiGraphics = guiGraphics; - GuiRenderer.setPoseStack(guiGraphics.pose()); - RenderSystem.enableBlend(); + VRenderSystem.enableBlend(); int size = minecraft.font.lineHeight * 4; - guiGraphics.blit(ICON, 30, 4, 0f, 0f, size, size, size, size); + guiGraphics.blit(ICON, 30, 4, 0, 0, size, size, size, size); VOptionList currentList = this.optionPages.get(this.currentListIdx).getOptionList(); currentList.updateState(mouseX, mouseY); diff --git a/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java index 20c601476..6e547f084 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/CyclingOptionWidget.java @@ -1,15 +1,11 @@ package net.vulkanmod.config.gui.widget; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.*; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; -import net.minecraft.client.renderer.GameRenderer; import net.minecraft.network.chat.Component; import net.vulkanmod.config.gui.GuiRenderer; import net.vulkanmod.config.option.CyclingOption; import net.vulkanmod.vulkan.util.ColorUtil; -import org.joml.Matrix4f; public class CyclingOptionWidget extends OptionWidget> { private Button leftButton; @@ -28,12 +24,10 @@ public CyclingOptionWidget(CyclingOption option, int x, int y, int width, int @Override protected int getYImage(boolean hovered) { - return 0; + return 0; } public void renderControls(double mouseX, double mouseY) { - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); - this.renderBars(); this.leftButton.setStatus(option.index() > 0); @@ -45,8 +39,8 @@ public void renderControls(double mouseX, double mouseY) { int y = this.y + (this.height - 9) / 2; GuiRenderer.drawCenteredString(textRenderer, this.getDisplayedValue(), x, y, color); - this.leftButton.renderButton(GuiRenderer.guiGraphics.pose(), mouseX, mouseY); - this.rightButton.renderButton(GuiRenderer.guiGraphics.pose(), mouseX, mouseY); + this.leftButton.render(mouseX, mouseY); + this.rightButton.render(mouseX, mouseY); } public void renderBars() { @@ -76,8 +70,7 @@ public void renderBars() { public void onClick(double mouseX, double mouseY) { if (leftButton.isHovered(mouseX, mouseY)) { option.prevValue(); - } - else if (rightButton.isHovered(mouseX, mouseY)) { + } else if (rightButton.isHovered(mouseX, mouseY)) { option.nextValue(); } } @@ -93,13 +86,13 @@ protected void onDrag(double mouseX, double mouseY, double deltaX, double deltaY } @Override - public void setFocused(boolean bl) { - this.focused = bl; + public boolean isFocused() { + return this.focused; } @Override - public boolean isFocused() { - return this.focused; + public void setFocused(boolean bl) { + this.focused = bl; } class Button { @@ -123,44 +116,21 @@ void setStatus(boolean status) { this.active = status; } - void renderButton(PoseStack matrices, double mouseX, double mouseY) { - Tesselator tesselator = Tesselator.getInstance(); - BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.TRIANGLE_STRIP, DefaultVertexFormat.POSITION); - - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); - - float f = this.isHovered(mouseX, mouseY) && this.active ? 5.0f : 4.5f; - - Matrix4f matrix4f = matrices.last().pose(); - - RenderSystem.setShader(GameRenderer::getPositionShader); - RenderSystem.enableBlend(); - - if(this.isHovered(mouseX, mouseY) && this.active) - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); - else if(this.active) - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 0.8f); - else - RenderSystem.setShaderColor(0.3f, 0.3f, 0.3f, 0.8f); - - float h = f; - float w = f - 1.0f; - float yC = y + height * 0.5f; - float xC = x + width * 0.5f; - if (this.direction == Direction.LEFT) { - bufferBuilder.addVertex(matrix4f, xC - w, yC, 0); - bufferBuilder.addVertex(matrix4f, xC + w, yC + h, 0); - bufferBuilder.addVertex(matrix4f, xC + w, yC - h, 0); + void render(double mouseX, double mouseY) { + boolean hovered = this.isHovered(mouseX, mouseY); + int color; + if (!this.active) { + color = 0x606060; } else { - bufferBuilder.addVertex(matrix4f, xC + w, yC, 0); - bufferBuilder.addVertex(matrix4f, xC - w, yC - h, 0); - bufferBuilder.addVertex(matrix4f, xC - w, yC + h, 0); + color = hovered ? 0xFFFFFF : 0xA0A0A0; } - BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); - - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); - RenderSystem.setShader(GameRenderer::getPositionTexShader); + String symbol = this.direction == Direction.LEFT ? "<" : ">"; + Font font = Minecraft.getInstance().font; + int textWidth = font.width(symbol); + int textX = this.x + (this.width - textWidth) / 2; + int textY = CyclingOptionWidget.this.y + (CyclingOptionWidget.this.height - 9) / 2; + GuiRenderer.drawString(font, Component.literal(symbol), textX, textY, color); } enum Direction { diff --git a/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java index a9fe679ce..7573e6a9e 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/OptionWidget.java @@ -1,34 +1,24 @@ package net.vulkanmod.config.gui.widget; -import com.mojang.blaze3d.systems.RenderSystem; -import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.narration.NarratableEntry; import net.minecraft.client.gui.narration.NarrationElementOutput; -import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.client.sounds.SoundManager; import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvents; -import net.minecraft.util.Mth; -import net.vulkanmod.config.gui.GuiElement; import net.vulkanmod.config.gui.GuiRenderer; -import net.vulkanmod.config.option.CyclingOption; import net.vulkanmod.config.option.Option; -import net.vulkanmod.render.util.MathUtil; +import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.util.ColorUtil; -import java.util.Objects; - public abstract class OptionWidget> extends VAbstractWidget implements NarratableEntry { + private final Component name; public int controlX; public int controlWidth; - private final Component name; protected Component displayedValue; protected boolean controlHovered; @@ -69,12 +59,10 @@ public void updateState() { public void renderWidget(double mouseX, double mouseY) { Minecraft minecraftClient = Minecraft.getInstance(); - RenderSystem.setShader(GameRenderer::getPositionTexShader); - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); + VRenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); int i = this.getYImage(this.isHovered()); - RenderSystem.enableBlend(); - RenderSystem.defaultBlendFunc(); - RenderSystem.enableDepthTest(); + VRenderSystem.enableBlend(); + VRenderSystem.enableDepthTest(); int xPadding = 0; int yPadding = 0; @@ -90,7 +78,7 @@ public void renderWidget(double mouseX, double mouseY) { Font textRenderer = minecraftClient.font; GuiRenderer.drawString(textRenderer, this.getName().getVisualOrderText(), this.x + 8, this.y + (this.height - 8) / 2, color); - RenderSystem.enableBlend(); + VRenderSystem.enableBlend(); this.renderControls(mouseX, mouseY); } @@ -155,21 +143,21 @@ public boolean mouseReleased(double mouseX, double mouseY, int button) { @Override public boolean isMouseOver(double mouseX, double mouseY) { - return this.active && this.visible && mouseX >= (double)this.x && mouseY >= (double)this.y && mouseX < (double)(this.x + this.width) && mouseY < (double)(this.y + this.height); + return this.active && this.visible && mouseX >= (double) this.x && mouseY >= (double) this.y && mouseX < (double) (this.x + this.width) && mouseY < (double) (this.y + this.height); } @Override - public void setFocused(boolean bl) { - this.focused = bl; + public boolean isFocused() { + return this.focused; } @Override - public boolean isFocused() { - return this.focused; + public void setFocused(boolean bl) { + this.focused = bl; } protected boolean clicked(double mouseX, double mouseY) { - return this.active && this.visible && mouseX >= (double)this.controlX && mouseY >= (double)this.y && mouseX < (double)(this.x + this.width) && mouseY < (double)(this.y + this.height); + return this.active && this.visible && mouseX >= (double) this.controlX && mouseY >= (double) this.y && mouseX < (double) (this.x + this.width) && mouseY < (double) (this.y + this.height); } public Component getName() { diff --git a/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java index 7cef7e107..25f91645d 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/RangeOptionWidget.java @@ -1,6 +1,5 @@ package net.vulkanmod.config.gui.widget; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.sounds.SoundManager; @@ -8,6 +7,7 @@ import net.minecraft.util.Mth; import net.vulkanmod.config.gui.GuiRenderer; import net.vulkanmod.config.option.RangeOption; +import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.util.ColorUtil; import org.lwjgl.glfw.GLFW; @@ -30,7 +30,7 @@ protected int getYImage(boolean hovered) { @Override protected void renderControls(double mouseX, double mouseY) { - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); + VRenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); int valueX = this.controlX + (int) (this.value * (this.controlWidth)); @@ -69,7 +69,6 @@ public void onClick(double mouseX, double mouseY) { this.setValueFromMouse(mouseX); } - @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { boolean isLeft = keyCode == GLFW.GLFW_KEY_LEFT; boolean isRight = keyCode == GLFW.GLFW_KEY_RIGHT; @@ -83,13 +82,13 @@ public boolean keyPressed(int keyCode, int scanCode, int modifiers) { } @Override - public void setFocused(boolean bl) { - this.focused = bl; + public boolean isFocused() { + return this.focused; } @Override - public boolean isFocused() { - return this.focused; + public void setFocused(boolean bl) { + this.focused = bl; } private void setValueFromMouse(double mouseX) { diff --git a/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java index 340902f3c..a6cfc71a0 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/SwitchOptionWidget.java @@ -41,7 +41,7 @@ protected void renderControls(double mouseX, double mouseY) { } color = ColorUtil.ARGB.pack(0.6f, 0.6f, 0.6f, 1.0f); - GuiRenderer.renderBoxBorder(x0, y0, halfWidth * 2, height, 1, color); + GuiRenderer.renderBoxBorder(x0, y0, halfWidth * 2, height, 1, color); color = this.active ? 0xFFFFFF : 0xA0A0A0; Font textRenderer = Minecraft.getInstance().font; @@ -77,13 +77,13 @@ protected void updateDisplayedValue() { } @Override - public void setFocused(boolean bl) { - this.focused = bl; + public boolean isFocused() { + return this.focused; } @Override - public boolean isFocused() { - return this.focused; + public void setFocused(boolean bl) { + this.focused = bl; } } diff --git a/src/main/java/net/vulkanmod/config/gui/widget/VAbstractWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/VAbstractWidget.java index 58bbd0d0e..a56483510 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/VAbstractWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/VAbstractWidget.java @@ -55,7 +55,6 @@ protected void renderHovering(int xPadding, int yPadding) { } } - @Override public boolean mouseClicked(double mX, double mY, int button) { if (this.active && this.visible) { if (this.isValidClickButton(button)) { @@ -74,13 +73,12 @@ public boolean mouseClicked(double mX, double mY, int button) { protected boolean clicked(double mX, double mY) { return this.active && this.visible - && mX >= (double)this.getX() - && mY >= (double)this.getY() - && mX < (double)(this.getX() + this.getWidth()) - && mY < (double)(this.getY() + this.getHeight()); + && mX >= (double) this.getX() + && mY >= (double) this.getY() + && mX < (double) (this.getX() + this.getWidth()) + && mY < (double) (this.getY() + this.getHeight()); } - @Override public boolean mouseReleased(double mX, double mY, int button) { if (this.isValidClickButton(button)) { this.onRelease(mX, mY); @@ -94,7 +92,6 @@ protected boolean isValidClickButton(int button) { return button == 0; } - @Override public boolean mouseDragged(double mX, double mY, int button, double f, double g) { if (this.isValidClickButton(button)) { this.onDrag(mX, mY, f, g); diff --git a/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java b/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java index 3664d9429..98fcab31e 100644 --- a/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java +++ b/src/main/java/net/vulkanmod/config/gui/widget/VButtonWidget.java @@ -1,12 +1,11 @@ package net.vulkanmod.config.gui.widget; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; -import net.minecraft.client.renderer.GameRenderer; import net.minecraft.network.chat.Component; import net.minecraft.util.Mth; import net.vulkanmod.config.gui.GuiRenderer; +import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.util.ColorUtil; import java.util.function.Consumer; @@ -27,10 +26,9 @@ public VButtonWidget(int x, int y, int width, int height, Component message, Con public void renderWidget(double mouseX, double mouseY) { Minecraft minecraftClient = Minecraft.getInstance(); Font textRenderer = minecraftClient.font; - RenderSystem.setShader(GameRenderer::getPositionTexShader); - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, this.alpha); + VRenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, this.alpha); - RenderSystem.enableBlend(); + VRenderSystem.enableBlend(); int xPadding = 0; int yPadding = 0; @@ -45,17 +43,17 @@ public void renderWidget(double mouseX, double mouseY) { int j = this.active ? 0xFFFFFF : 0xA0A0A0; GuiRenderer.drawCenteredString(textRenderer, this.message, this.x + this.width / 2, this.y + (this.height - 8) / 2, j | Mth.ceil(this.alpha * 255.0f) << 24); - RenderSystem.enableBlend(); + VRenderSystem.enableBlend(); - if(this.selected) { + if (this.selected) { // color = ColorUtil.ARGB.pack(1.0f, 1.0f, 1.0f, 1.0f); color = ColorUtil.ARGB.pack(0.3f, 0.0f, 0.0f, 1.0f); // GuiRenderer.fillBox(this.x, this.y + this.height - 1, this.width, 1, color); - GuiRenderer.fillBox(this.x, this.y, 1.5f, this.height, color); + GuiRenderer.fillBox(this.x, this.y, 1.5f, this.height, color); // color = ColorUtil.ARGB.pack(0.5f, 0.5f, 0.5f, 0.2f); color = ColorUtil.ARGB.pack(0.3f, 0.0f, 0.0f, 0.2f); - GuiRenderer.fillBox(this.x, this.y, this.width, this.height, color); + GuiRenderer.fillBox(this.x, this.y, this.width, this.height, color); } } diff --git a/src/main/java/net/vulkanmod/config/option/CyclingOption.java b/src/main/java/net/vulkanmod/config/option/CyclingOption.java index d6080f7fd..a8ec440bd 100644 --- a/src/main/java/net/vulkanmod/config/option/CyclingOption.java +++ b/src/main/java/net/vulkanmod/config/option/CyclingOption.java @@ -32,26 +32,24 @@ public void updateOption(E[] values, Consumer setter, Supplier getter) { this.index = ArrayUtils.indexOf(this.values, this.getNewValue()); } - public int index() { return this.index; } - - public void setValues(E[] values) { - this.values = values; + public int index() { + return this.index; } public void prevValue() { - if(this.index > 0) + if (this.index > 0) this.index--; this.updateValue(); } public void nextValue() { - if(this.index < values.length - 1) + if (this.index < values.length - 1) this.index++; this.updateValue(); } private void updateValue() { - if(this.index >= 0 && this.index < this.values.length) { + if (this.index >= 0 && this.index < this.values.length) { this.newValue = values[this.index]; if (onChange != null) @@ -75,4 +73,8 @@ private int findNewValueIndex() { public E[] getValues() { return values; } + + public void setValues(E[] values) { + this.values = values; + } } diff --git a/src/main/java/net/vulkanmod/config/option/Option.java b/src/main/java/net/vulkanmod/config/option/Option.java index a1425ccf8..8d24507ce 100644 --- a/src/main/java/net/vulkanmod/config/option/Option.java +++ b/src/main/java/net/vulkanmod/config/option/Option.java @@ -64,13 +64,6 @@ public Option setActive(boolean active) { public abstract OptionWidget createOptionWidget(int x, int y, int width, int height); - public void setNewValue(T t) { - this.newValue = t; - - if (onChange != null) - onChange.run(); - } - public Component getName() { return this.name; } @@ -84,7 +77,7 @@ public boolean isChanged() { } public void apply() { - if(!isChanged()) + if (!isChanged()) return; onApply.accept(this.newValue); @@ -95,16 +88,23 @@ public T getNewValue() { return this.newValue; } + public void setNewValue(T t) { + this.newValue = t; + + if (onChange != null) + onChange.run(); + } + public Component getDisplayedValue() { return this.translator.apply(this.newValue); } + public Component getTooltip() { + return this.tooltip; + } + public Option setTooltip(Component text) { this.tooltip = text; return this; } - - public Component getTooltip() { - return this.tooltip; - } } diff --git a/src/main/java/net/vulkanmod/config/option/OptionPage.java b/src/main/java/net/vulkanmod/config/option/OptionPage.java index 8d783fe4e..d6332e15e 100644 --- a/src/main/java/net/vulkanmod/config/option/OptionPage.java +++ b/src/main/java/net/vulkanmod/config/option/OptionPage.java @@ -41,4 +41,4 @@ public void applyOptionChanges() { } } } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/config/option/Options.java b/src/main/java/net/vulkanmod/config/option/Options.java index c52a8de73..44b4c1f23 100644 --- a/src/main/java/net/vulkanmod/config/option/Options.java +++ b/src/main/java/net/vulkanmod/config/option/Options.java @@ -3,6 +3,7 @@ import com.mojang.blaze3d.platform.Window; import net.minecraft.client.*; import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ParticleStatus; import net.vulkanmod.Initializer; import net.vulkanmod.config.Config; import net.vulkanmod.config.gui.OptionBlock; @@ -84,7 +85,7 @@ public static OptionBlock[] getVideoOpts() { value -> { boolean exclusiveFullscreen = value == WindowMode.EXCLUSIVE_FULLSCREEN; minecraftOptions.fullscreen() - .set(exclusiveFullscreen); + .set(exclusiveFullscreen); config.windowMode = value.mode; fullscreenDirty = true; @@ -98,7 +99,7 @@ public static OptionBlock[] getVideoOpts() { String.valueOf(value)), value -> { minecraftOptions.framerateLimit().set(value); - window.setFramerateLimit(value); + minecraft.getFramerateLimitTracker().setFramerateLimit(value); }, () -> minecraftOptions.framerateLimit().get()), new SwitchOption(Component.translatable("options.vsync"), @@ -279,12 +280,12 @@ public static OptionBlock[] getOtherOpts() { return new OptionBlock[]{ new OptionBlock("", new Option[]{ new RangeOption(Component.translatable("vulkanmod.options.builderThreads"), - 0, (Runtime.getRuntime().availableProcessors() - 1), 1, - value -> { - config.builderThreads = value; - WorldRenderer.getInstance().getTaskDispatcher().createThreads(value); - }, - () -> config.builderThreads) + 0, (Runtime.getRuntime().availableProcessors() - 1), 1, + value -> { + config.builderThreads = value; + WorldRenderer.getInstance().getTaskDispatcher().createThreads(value); + }, + () -> config.builderThreads) .setTranslator(value -> { if (value == 0) return Component.translatable("vulkanmod.options.builderThreads.auto"); diff --git a/src/main/java/net/vulkanmod/config/video/VideoModeManager.java b/src/main/java/net/vulkanmod/config/video/VideoModeManager.java index 985455a63..7e28e0b48 100644 --- a/src/main/java/net/vulkanmod/config/video/VideoModeManager.java +++ b/src/main/java/net/vulkanmod/config/video/VideoModeManager.java @@ -7,14 +7,13 @@ import java.util.ArrayList; import java.util.List; -import static org.lwjgl.glfw.GLFW.*; +import static org.lwjgl.glfw.GLFW.glfwGetPrimaryMonitor; public abstract class VideoModeManager { + public static VideoModeSet.VideoMode selectedVideoMode; private static VideoModeSet.VideoMode osVideoMode; private static VideoModeSet[] videoModeSets; - public static VideoModeSet.VideoMode selectedVideoMode; - public static void init() { long monitor = glfwGetPrimaryMonitor(); osVideoMode = getCurrentVideoMode(monitor); @@ -30,7 +29,7 @@ public static VideoModeSet[] getVideoResolutions() { } public static VideoModeSet getFirstAvailable() { - if(videoModeSets != null) + if (videoModeSets != null) return videoModeSets[videoModeSets.length - 1]; else return VideoModeSet.getDummy(); @@ -40,7 +39,7 @@ public static VideoModeSet.VideoMode getOsVideoMode() { return osVideoMode; } - public static VideoModeSet.VideoMode getCurrentVideoMode(long monitor){ + public static VideoModeSet.VideoMode getCurrentVideoMode(long monitor) { GLFWVidMode vidMode = GLFW.glfwGetVideoMode(monitor); if (vidMode == null) diff --git a/src/main/java/net/vulkanmod/config/video/VideoModeSet.java b/src/main/java/net/vulkanmod/config/video/VideoModeSet.java index e4fb34fac..a49246981 100644 --- a/src/main/java/net/vulkanmod/config/video/VideoModeSet.java +++ b/src/main/java/net/vulkanmod/config/video/VideoModeSet.java @@ -10,18 +10,18 @@ public class VideoModeSet { public final int bitDepth; List refreshRates = new ObjectArrayList<>(); - public static VideoModeSet getDummy() { - var set = new VideoModeSet(-1, -1, -1); - set.addRefreshRate(-1); - return set; - } - public VideoModeSet(int width, int height, int bitDepth) { this.width = width; this.height = height; this.bitDepth = bitDepth; } + public static VideoModeSet getDummy() { + var set = new VideoModeSet(-1, -1, -1); + set.addRefreshRate(-1); + return set; + } + public int getRefreshRate() { return this.refreshRates.get(0); } @@ -90,6 +90,6 @@ public String toString() { "refreshRate=" + refreshRate + ']'; } - } + } } diff --git a/src/main/java/net/vulkanmod/config/video/WindowMode.java b/src/main/java/net/vulkanmod/config/video/WindowMode.java index 621f06dea..3af627a2c 100644 --- a/src/main/java/net/vulkanmod/config/video/WindowMode.java +++ b/src/main/java/net/vulkanmod/config/video/WindowMode.java @@ -28,4 +28,4 @@ public static String getComponentName(WindowMode windowMode) { case EXCLUSIVE_FULLSCREEN -> "options.fullscreen"; }; } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/gl/GlUtil.java b/src/main/java/net/vulkanmod/gl/GlUtil.java index fe8edea75..2112a01a2 100644 --- a/src/main/java/net/vulkanmod/gl/GlUtil.java +++ b/src/main/java/net/vulkanmod/gl/GlUtil.java @@ -29,7 +29,7 @@ public static ByteBuffer RGBtoRGBA_buffer(ByteBuffer in) { ByteBuffer out = MemoryUtil.memAlloc(outSize); int j = 0; - for (int i = 0; i < outSize; i+=4, j+=3) { + for (int i = 0; i < outSize; i += 4, j += 3) { out.put(i, in.get(j)); out.put(i + 1, in.get(j + 1)); out.put(i + 2, in.get(j + 2)); @@ -50,7 +50,7 @@ public static ByteBuffer BGRAtoRGBA_buffer(ByteBuffer in) { long srcPtr = MemoryUtil.memAddress0(in); // TODO write in place (don't free the returned buffer in that case) - for (int i = 0; i < outSize ; i += 4) { + for (int i = 0; i < outSize; i += 4) { int color = MemoryUtil.memGetInt(srcPtr + i); color = (color << 24) & 0xFF000000 | (color >> 8) & 0xFFFFFF; @@ -63,34 +63,29 @@ public static ByteBuffer BGRAtoRGBA_buffer(ByteBuffer in) { public static int vulkanFormat(int glFormat, int type) { return switch (glFormat) { - case GL11.GL_RGBA, GL30.GL_RGBA8 -> - switch (type) { - case GL11.GL_UNSIGNED_BYTE -> VK_FORMAT_R8G8B8A8_UNORM; - case GL11.GL_BYTE -> VK_FORMAT_R8G8B8A8_UNORM; - case GL30.GL_UNSIGNED_INT_8_8_8_8, GL30.GL_UNSIGNED_INT_8_8_8_8_REV -> VK_FORMAT_R8G8B8A8_UNORM; - default -> throw new IllegalStateException("Unexpected type: " + type); - }; - case GL30.GL_BGRA -> - switch (type) { - case GL11.GL_UNSIGNED_BYTE -> VK_FORMAT_B8G8R8A8_UNORM; - case GL11.GL_BYTE -> VK_FORMAT_B8G8R8A8_UNORM; - case GL30.GL_UNSIGNED_INT_8_8_8_8, GL30.GL_UNSIGNED_INT_8_8_8_8_REV -> VK_FORMAT_B8G8R8A8_UNORM; - default -> throw new IllegalStateException("Unexpected type: " + type); - }; - case GL30.GL_UNSIGNED_INT_8_8_8_8_REV -> - switch (type) { - case GL11.GL_UNSIGNED_BYTE -> VK_FORMAT_R8G8B8A8_UINT; - case GL11.GL_BYTE -> VK_FORMAT_R8G8B8A8_UNORM; - default -> throw new IllegalStateException("Unexpected type: " + type); - }; - case GL11.GL_RED -> - switch (type) { - case GL11.GL_UNSIGNED_BYTE -> VK_FORMAT_R8_UNORM; - default -> throw new IllegalStateException("Unexpected type: " + type); - }; + case GL11.GL_RGBA, GL30.GL_RGBA8 -> switch (type) { + case GL11.GL_UNSIGNED_BYTE -> VK_FORMAT_R8G8B8A8_UNORM; + case GL11.GL_BYTE -> VK_FORMAT_R8G8B8A8_UNORM; + case GL30.GL_UNSIGNED_INT_8_8_8_8, GL30.GL_UNSIGNED_INT_8_8_8_8_REV -> VK_FORMAT_R8G8B8A8_UNORM; + default -> throw new IllegalStateException("Unexpected type: " + type); + }; + case GL30.GL_BGRA -> switch (type) { + case GL11.GL_UNSIGNED_BYTE -> VK_FORMAT_B8G8R8A8_UNORM; + case GL11.GL_BYTE -> VK_FORMAT_B8G8R8A8_UNORM; + case GL30.GL_UNSIGNED_INT_8_8_8_8, GL30.GL_UNSIGNED_INT_8_8_8_8_REV -> VK_FORMAT_B8G8R8A8_UNORM; + default -> throw new IllegalStateException("Unexpected type: " + type); + }; + case GL30.GL_UNSIGNED_INT_8_8_8_8_REV -> switch (type) { + case GL11.GL_UNSIGNED_BYTE -> VK_FORMAT_R8G8B8A8_UINT; + case GL11.GL_BYTE -> VK_FORMAT_R8G8B8A8_UNORM; + default -> throw new IllegalStateException("Unexpected type: " + type); + }; + case GL11.GL_RED -> switch (type) { + case GL11.GL_UNSIGNED_BYTE -> VK_FORMAT_R8_UNORM; + default -> throw new IllegalStateException("Unexpected type: " + type); + }; case GL11.GL_DEPTH_COMPONENT, GL30.GL_DEPTH_COMPONENT32, - GL30.GL_DEPTH_COMPONENT32F, GL30.GL_DEPTH_COMPONENT24 -> - Vulkan.getDefaultDepthFormat(); + GL30.GL_DEPTH_COMPONENT32F, GL30.GL_DEPTH_COMPONENT24 -> Vulkan.getDefaultDepthFormat(); default -> throw new IllegalStateException("Unexpected format: " + glFormat); }; diff --git a/src/main/java/net/vulkanmod/gl/VkGlBuffer.java b/src/main/java/net/vulkanmod/gl/VkGlBuffer.java index 05cc59be1..b35bdafc3 100644 --- a/src/main/java/net/vulkanmod/gl/VkGlBuffer.java +++ b/src/main/java/net/vulkanmod/gl/VkGlBuffer.java @@ -10,13 +10,20 @@ // TODO: This class is only used to emulate a CPU buffer for texture copying purposes // any other use is not supported public class VkGlBuffer { - private static int ID_COUNTER = 1; private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); + private static int ID_COUNTER = 1; private static int boundId = 0; private static VkGlBuffer boundBuffer; private static VkGlBuffer pixelPackBufferBound; private static VkGlBuffer pixelUnpackBufferBound; + int id; + int target; + ByteBuffer data; + + public VkGlBuffer(int id) { + this.id = id; + } public static int glGenBuffers() { int id = ID_COUNTER; @@ -103,15 +110,6 @@ private static void checkTarget(int target) { throw new IllegalArgumentException("target %d not supported".formatted(target)); } - int id; - int target; - - ByteBuffer data; - - public VkGlBuffer(int id) { - this.id = id; - } - private void allocate(int size) { if (this.data != null) this.freeData(); diff --git a/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java b/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java index 9981da56f..2effa7f6c 100644 --- a/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java +++ b/src/main/java/net/vulkanmod/gl/VkGlFramebuffer.java @@ -10,15 +10,23 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL30; -import static org.lwjgl.vulkan.VK11.VK_ATTACHMENT_LOAD_OP_LOAD; -import static org.lwjgl.vulkan.VK11.VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; +import static org.lwjgl.vulkan.VK10.VK_ATTACHMENT_LOAD_OP_LOAD; +import static org.lwjgl.vulkan.VK10.VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; public class VkGlFramebuffer { - private static int idCounter = 1; - private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); + private static int idCounter = 1; private static VkGlFramebuffer boundFramebuffer; private static VkGlFramebuffer readFramebuffer; + public final int id; + Framebuffer framebuffer; + RenderPass renderPass; + VulkanImage colorAttachment; + VulkanImage depthAttachment; + + VkGlFramebuffer(int i) { + this.id = i; + } public static void resetBoundFramebuffer() { boundFramebuffer = null; @@ -138,22 +146,21 @@ public static VkGlFramebuffer getFramebuffer(int id) { return map.get(id); } - public final int id; - Framebuffer framebuffer; - RenderPass renderPass; - - VulkanImage colorAttachment; - VulkanImage depthAttachment; - - VkGlFramebuffer(int i) { - this.id = i; - } - boolean beginRendering() { return Renderer.getInstance().beginRendering(this.renderPass, this.framebuffer); } void setAttachmentTexture(int attachment, int texture) { + if (texture == 0) { + switch (attachment) { + case GL30.GL_COLOR_ATTACHMENT0 -> this.colorAttachment = null; + case GL30.GL_DEPTH_ATTACHMENT -> this.depthAttachment = null; + default -> { + } + } + return; + } + VkGlTexture glTexture = VkGlTexture.getTexture(texture); if (glTexture == null) @@ -211,16 +218,16 @@ void createAndBind() { VulkanImage depthImage = this.depthAttachment; this.framebuffer = Framebuffer.builder(this.colorAttachment, depthImage) - .build(); + .build(); RenderPass.Builder builder = RenderPass.builder(this.framebuffer); builder.getColorAttachmentInfo() - .setLoadOp(VK_ATTACHMENT_LOAD_OP_LOAD) - .setFinalLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + .setLoadOp(VK_ATTACHMENT_LOAD_OP_LOAD) + .setFinalLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); if (hasDepthImage) { builder.getDepthAttachmentInfo() - .setOps(VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_LOAD_OP_LOAD); + .setOps(VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_LOAD_OP_LOAD); } this.renderPass = builder.build(); diff --git a/src/main/java/net/vulkanmod/gl/VkGlProgram.java b/src/main/java/net/vulkanmod/gl/VkGlProgram.java index 2cce606f2..38fe4829b 100644 --- a/src/main/java/net/vulkanmod/gl/VkGlProgram.java +++ b/src/main/java/net/vulkanmod/gl/VkGlProgram.java @@ -4,10 +4,16 @@ import net.vulkanmod.vulkan.shader.Pipeline; public class VkGlProgram { - private static int ID_COUNTER = 1; private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); + private static int ID_COUNTER = 1; private static int boundProgramId = 0; private static VkGlProgram boundProgram; + int id; + Pipeline pipeline; + + VkGlProgram(int i) { + this.id = i; + } public static VkGlProgram getBoundProgram() { return boundProgram; @@ -38,13 +44,6 @@ public static void glUseProgram(int id) { } - int id; - Pipeline pipeline; - - VkGlProgram(int i) { - this.id = i; - } - public void bindPipeline(Pipeline pipeline) { this.pipeline = pipeline; } diff --git a/src/main/java/net/vulkanmod/gl/VkGlRenderbuffer.java b/src/main/java/net/vulkanmod/gl/VkGlRenderbuffer.java index e811144a2..453996896 100644 --- a/src/main/java/net/vulkanmod/gl/VkGlRenderbuffer.java +++ b/src/main/java/net/vulkanmod/gl/VkGlRenderbuffer.java @@ -14,10 +14,21 @@ import static org.lwjgl.vulkan.VK10.*; public class VkGlRenderbuffer { - private static int ID_COUNTER = 1; private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); + private static int ID_COUNTER = 1; private static int boundId = 0; private static VkGlRenderbuffer bound; + final int id; + VulkanImage vulkanImage; + int internalFormat; + boolean needsUpdate = false; + int maxLevel = 0; + int maxLod = 0; + int minFilter, magFilter = GL11.GL_LINEAR; + + public VkGlRenderbuffer(int id) { + this.id = id; + } public static int genId() { int id = ID_COUNTER; @@ -65,8 +76,10 @@ public static void texParameteri(int target, int pName, int param) { switch (pName) { case GL30.GL_TEXTURE_MAX_LEVEL -> bound.setMaxLevel(param); case GL30.GL_TEXTURE_MAX_LOD -> bound.setMaxLod(param); - case GL30.GL_TEXTURE_MIN_LOD -> {} - case GL30.GL_TEXTURE_LOD_BIAS -> {} + case GL30.GL_TEXTURE_MIN_LOD -> { + } + case GL30.GL_TEXTURE_LOD_BIAS -> { + } case GL11.GL_TEXTURE_MAG_FILTER -> bound.setMagFilter(param); case GL11.GL_TEXTURE_MIN_FILTER -> bound.setMinFilter(param); @@ -108,19 +121,6 @@ public static VkGlRenderbuffer getBound() { return bound; } - final int id; - VulkanImage vulkanImage; - int internalFormat; - - boolean needsUpdate = false; - int maxLevel = 0; - int maxLod = 0; - int minFilter, magFilter = GL11.GL_LINEAR; - - public VkGlRenderbuffer(int id) { - this.id = id; - } - void allocateIfNeeded(int width, int height, int format) { int vkFormat = GlUtil.vulkanFormat(format); diff --git a/src/main/java/net/vulkanmod/gl/VkGlTexture.java b/src/main/java/net/vulkanmod/gl/VkGlTexture.java index 7f01144a2..708c44d94 100644 --- a/src/main/java/net/vulkanmod/gl/VkGlTexture.java +++ b/src/main/java/net/vulkanmod/gl/VkGlTexture.java @@ -17,8 +17,8 @@ import static org.lwjgl.vulkan.VK10.*; public class VkGlTexture { - private static int ID_COUNTER = 1; private static final Int2ReferenceOpenHashMap map = new Int2ReferenceOpenHashMap<>(); + private static int ID_COUNTER = 1; private static int boundTextureId = 0; private static VkGlTexture boundTexture; private static int activeTexture = 0; @@ -26,6 +26,19 @@ public class VkGlTexture { private static int unpackRowLength; private static int unpackSkipRows; private static int unpackSkipPixels; + public final int id; + VulkanImage vulkanImage; + int width, height; + int vkFormat; + boolean needsUpdate = false; + int maxLevel = 0; + int maxLod = 0; + int minFilter, magFilter = GL11.GL_LINEAR; + boolean clamp = true; + + public VkGlTexture(int id) { + this.id = id; + } public static void bindIdToImage(int id, VulkanImage vulkanImage) { VkGlTexture texture = map.get(id); @@ -143,7 +156,7 @@ private static ByteBuffer getByteBuffer(int width, int height, long pixels) { return src; } - public static void texSubImage2D(int target, int level, int xOffset, int yOffset, int width , int height, int format, int type, @Nullable ByteBuffer pixels) { + public static void texSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int type, @Nullable ByteBuffer pixels) { if (width == 0 || height == 0) return; @@ -175,15 +188,18 @@ public static void texParameteri(int target, int pName, int param) { switch (pName) { case GL30.GL_TEXTURE_MAX_LEVEL -> boundTexture.setMaxLevel(param); case GL30.GL_TEXTURE_MAX_LOD -> boundTexture.setMaxLod(param); - case GL30.GL_TEXTURE_MIN_LOD -> {} - case GL30.GL_TEXTURE_LOD_BIAS -> {} + case GL30.GL_TEXTURE_MIN_LOD -> { + } + case GL30.GL_TEXTURE_LOD_BIAS -> { + } case GL11.GL_TEXTURE_MAG_FILTER -> boundTexture.setMagFilter(param); case GL11.GL_TEXTURE_MIN_FILTER -> boundTexture.setMinFilter(param); case GL11.GL_TEXTURE_WRAP_S, GL11.GL_TEXTURE_WRAP_T -> boundTexture.setClamp(param); - default -> {} + default -> { + } } //TODO @@ -270,23 +286,6 @@ public static VkGlTexture getBoundTexture() { return boundTexture; } - public final int id; - VulkanImage vulkanImage; - - int width, height; - int vkFormat; - - boolean needsUpdate = false; - int maxLevel = 0; - int maxLod = 0; - int minFilter, magFilter = GL11.GL_LINEAR; - - boolean clamp = true; - - public VkGlTexture(int id) { - this.id = id; - } - void updateParams(int level, int width, int height, int internalFormat, int type) { if (level > this.maxLevel) { this.maxLevel = level; @@ -325,8 +324,7 @@ void allocateImage(int width, int height, int vkFormat) { vkFormat, width, height, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, false, true); - } - else { + } else { this.vulkanImage = new VulkanImage.Builder(width, height) .setName(String.format("GlTexture %d", this.id)) .setMipLevels(maxLevel + 1) @@ -345,7 +343,8 @@ void updateSampler() { samplerFlags |= magFilter == GL11.GL_LINEAR ? SamplerManager.LINEAR_FILTERING_BIT : 0; samplerFlags |= switch (minFilter) { - case GL11.GL_LINEAR_MIPMAP_LINEAR -> SamplerManager.USE_MIPMAPS_BIT | SamplerManager.MIPMAP_LINEAR_FILTERING_BIT; + case GL11.GL_LINEAR_MIPMAP_LINEAR -> + SamplerManager.USE_MIPMAPS_BIT | SamplerManager.MIPMAP_LINEAR_FILTERING_BIT; case GL11.GL_NEAREST_MIPMAP_NEAREST -> SamplerManager.USE_MIPMAPS_BIT; default -> 0; }; diff --git a/src/main/java/net/vulkanmod/interfaces/ExtendedRenderType.java b/src/main/java/net/vulkanmod/interfaces/ExtendedRenderType.java index 17019659e..3fd82473b 100644 --- a/src/main/java/net/vulkanmod/interfaces/ExtendedRenderType.java +++ b/src/main/java/net/vulkanmod/interfaces/ExtendedRenderType.java @@ -5,4 +5,4 @@ public interface ExtendedRenderType { TerrainRenderType getTerrainRenderType(); -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/interfaces/ExtendedVertexBuilder.java b/src/main/java/net/vulkanmod/interfaces/ExtendedVertexBuilder.java index 441fe41b3..1df44ac89 100644 --- a/src/main/java/net/vulkanmod/interfaces/ExtendedVertexBuilder.java +++ b/src/main/java/net/vulkanmod/interfaces/ExtendedVertexBuilder.java @@ -19,5 +19,6 @@ default boolean canUseFastVertex() { void vertex(float x, float y, float z, int packedColor, float u, float v, int overlay, int light, int packedNormal); // Used for particles - default void vertex(float x, float y, float z, float u, float v, int packedColor, int light) {} -} + default void vertex(float x, float y, float z, float u, float v, int packedColor, int light) { + } +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/interfaces/FrustumMixed.java b/src/main/java/net/vulkanmod/interfaces/FrustumMixed.java index 2de91dcef..f5e472488 100644 --- a/src/main/java/net/vulkanmod/interfaces/FrustumMixed.java +++ b/src/main/java/net/vulkanmod/interfaces/FrustumMixed.java @@ -5,4 +5,4 @@ public interface FrustumMixed { VFrustum customFrustum(); -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/interfaces/GlShaderModuleExt.java b/src/main/java/net/vulkanmod/interfaces/GlShaderModuleExt.java new file mode 100644 index 000000000..806c94023 --- /dev/null +++ b/src/main/java/net/vulkanmod/interfaces/GlShaderModuleExt.java @@ -0,0 +1,7 @@ +package net.vulkanmod.interfaces; + +public interface GlShaderModuleExt { + void vulkanmod$setProcessedSource(String source); + + String vulkanmod$getProcessedSource(); +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/interfaces/ModelPartCubeMixed.java b/src/main/java/net/vulkanmod/interfaces/ModelPartCubeMixed.java deleted file mode 100644 index 23b1e9a6d..000000000 --- a/src/main/java/net/vulkanmod/interfaces/ModelPartCubeMixed.java +++ /dev/null @@ -1,8 +0,0 @@ -package net.vulkanmod.interfaces; - -import net.vulkanmod.render.model.CubeModel; - -public interface ModelPartCubeMixed { - - CubeModel getCubeModel(); -} diff --git a/src/main/java/net/vulkanmod/interfaces/ShaderMixed.java b/src/main/java/net/vulkanmod/interfaces/ShaderMixed.java deleted file mode 100644 index e05a698d4..000000000 --- a/src/main/java/net/vulkanmod/interfaces/ShaderMixed.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.vulkanmod.interfaces; - -import net.minecraft.client.renderer.ShaderInstance; -import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import net.vulkanmod.vulkan.shader.descriptor.UBO; -import net.vulkanmod.vulkan.util.MappedBuffer; - -import java.util.function.Supplier; - -public interface ShaderMixed { - - static ShaderMixed of(ShaderInstance compiledShaderProgram) { - return (ShaderMixed) compiledShaderProgram; - } - - void setPipeline(GraphicsPipeline graphicsPipeline); - - GraphicsPipeline getPipeline(); - - void setupUniformSuppliers(UBO ubo); - - Supplier getUniformSupplier(String name); - - void setDoUniformsUpdate(); -} diff --git a/src/main/java/net/vulkanmod/interfaces/VertexFormatMixed.java b/src/main/java/net/vulkanmod/interfaces/VertexFormatMixed.java index bd079bb16..a0043c9d8 100644 --- a/src/main/java/net/vulkanmod/interfaces/VertexFormatMixed.java +++ b/src/main/java/net/vulkanmod/interfaces/VertexFormatMixed.java @@ -9,4 +9,4 @@ public interface VertexFormatMixed { int getOffset(int i); List getFastList(); -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/interfaces/VisibilitySetExtended.java b/src/main/java/net/vulkanmod/interfaces/VisibilitySetExtended.java index 0aaba2a8f..407eda305 100644 --- a/src/main/java/net/vulkanmod/interfaces/VisibilitySetExtended.java +++ b/src/main/java/net/vulkanmod/interfaces/VisibilitySetExtended.java @@ -3,4 +3,4 @@ public interface VisibilitySetExtended { long getVisibility(); -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/interfaces/VoxelShapeExtended.java b/src/main/java/net/vulkanmod/interfaces/VoxelShapeExtended.java index 7d9d87709..e8f375e6b 100644 --- a/src/main/java/net/vulkanmod/interfaces/VoxelShapeExtended.java +++ b/src/main/java/net/vulkanmod/interfaces/VoxelShapeExtended.java @@ -3,4 +3,4 @@ public interface VoxelShapeExtended { int getCornerOcclusion(); -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/interfaces/biome/BiomeManagerExtended.java b/src/main/java/net/vulkanmod/interfaces/biome/BiomeManagerExtended.java index 6cb365021..80740983f 100644 --- a/src/main/java/net/vulkanmod/interfaces/biome/BiomeManagerExtended.java +++ b/src/main/java/net/vulkanmod/interfaces/biome/BiomeManagerExtended.java @@ -10,4 +10,4 @@ static BiomeManagerExtended of(BiomeManager biomeManager) { long getBiomeZoomSeed(); -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/chunk/ClientChunkCacheM.java b/src/main/java/net/vulkanmod/mixin/chunk/ClientChunkCacheM.java index 0b32f688b..577c05891 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/ClientChunkCacheM.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/ClientChunkCacheM.java @@ -30,4 +30,4 @@ private void setChunkStatus(int x, int z, FriendlyByteBuf friendlyByteBuf, Compo private void resetChunkStatus(ChunkPos chunkPos, CallbackInfo ci) { ChunkStatusMap.INSTANCE.resetChunkStatus(chunkPos.x, chunkPos.z, ChunkStatusMap.DATA_READY); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/chunk/ClientPacketListenerM.java b/src/main/java/net/vulkanmod/mixin/chunk/ClientPacketListenerM.java index dd2368259..60da0853c 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/ClientPacketListenerM.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/ClientPacketListenerM.java @@ -14,7 +14,7 @@ public class ClientPacketListenerM { @Inject(method = "applyLightData", at = @At("RETURN")) - private void setChunkStatus(int x, int z, ClientboundLightUpdatePacketData clientboundLightUpdatePacketData, CallbackInfo ci) { + private void setChunkStatus(int x, int z, ClientboundLightUpdatePacketData clientboundLightUpdatePacketData, boolean queued, CallbackInfo ci) { ChunkStatusMap.INSTANCE.setChunkStatus(x, z, ChunkStatusMap.LIGHT_READY); } diff --git a/src/main/java/net/vulkanmod/mixin/chunk/DirectionMixin.java b/src/main/java/net/vulkanmod/mixin/chunk/DirectionMixin.java index 81b0248d3..3a05be7df 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/DirectionMixin.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/DirectionMixin.java @@ -9,9 +9,13 @@ @Mixin(Direction.class) public class DirectionMixin { - @Shadow @Final private static Direction[] BY_3D_DATA; + @Shadow + @Final + private static Direction[] BY_3D_DATA; - @Shadow @Final private int oppositeIndex; + @Shadow + @Final + private int oppositeIndex; /** * @author @@ -21,4 +25,4 @@ public class DirectionMixin { public Direction getOpposite() { return BY_3D_DATA[this.oppositeIndex]; } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/chunk/FrustumMixin.java b/src/main/java/net/vulkanmod/mixin/chunk/FrustumMixin.java index 4959c34d2..088119ebc 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/FrustumMixin.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/FrustumMixin.java @@ -13,10 +13,13 @@ @Mixin(Frustum.class) public class FrustumMixin implements FrustumMixed { - @Shadow private double camX; - @Shadow private double camY; - @Shadow private double camZ; private final VFrustum vFrustum = new VFrustum(); + @Shadow + private double camX; + @Shadow + private double camY; + @Shadow + private double camZ; @Inject(method = "calculateFrustum", at = @At("HEAD"), cancellable = true) private void calculateFrustum(Matrix4f modelView, Matrix4f projection, CallbackInfo ci) { @@ -34,4 +37,4 @@ public void prepare(double d, double e, double f, CallbackInfo ci) { public VFrustum customFrustum() { return vFrustum; } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java b/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java index 394213f7b..9108183da 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/LevelRendererMixin.java @@ -16,7 +16,10 @@ import net.minecraft.world.phys.Vec3; import net.vulkanmod.render.chunk.WorldRenderer; import org.joml.Matrix4f; -import org.spongepowered.asm.mixin.*; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; @@ -27,10 +30,12 @@ @Mixin(LevelRenderer.class) public abstract class LevelRendererMixin { - @Shadow @Final + @Shadow + @Final private RenderBuffers renderBuffers; - @Shadow @Final + @Shadow + @Final private Long2ObjectMap> destructionProgress; private WorldRenderer worldRenderer; @@ -134,4 +139,4 @@ private float getRenderDistanceZFar(GameRenderer instance) { return instance.getRenderDistance() * 4F; } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/chunk/SectionBufferBuilderPoolM.java b/src/main/java/net/vulkanmod/mixin/chunk/SectionBufferBuilderPoolM.java index 18e653849..9554aedd7 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/SectionBufferBuilderPoolM.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/SectionBufferBuilderPoolM.java @@ -8,8 +8,8 @@ @Mixin(SectionBufferBuilderPool.class) public class SectionBufferBuilderPoolM { - @ModifyVariable(method = "allocate", at = @At("STORE"), ordinal = 1) - private static int skipAllocation(int value) { - return 0; - } -} + @ModifyVariable(method = "allocate", at = @At("STORE"), ordinal = 1) + private static int skipAllocation(int value) { + return 0; + } +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/chunk/SectionRenderDispatcherM.java b/src/main/java/net/vulkanmod/mixin/chunk/SectionRenderDispatcherM.java deleted file mode 100644 index 9dbdab773..000000000 --- a/src/main/java/net/vulkanmod/mixin/chunk/SectionRenderDispatcherM.java +++ /dev/null @@ -1,14 +0,0 @@ -package net.vulkanmod.mixin.chunk; - -import net.minecraft.client.renderer.chunk.SectionRenderDispatcher; -import net.minecraft.util.thread.ProcessorMailbox; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -@Mixin(SectionRenderDispatcher.class) -public class SectionRenderDispatcherM { - - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/thread/ProcessorMailbox;tell(Ljava/lang/Object;)V")) - private void redirectTask(ProcessorMailbox instance, Object object) {} -} diff --git a/src/main/java/net/vulkanmod/mixin/chunk/ViewAreaM.java b/src/main/java/net/vulkanmod/mixin/chunk/ViewAreaM.java index ef958df3f..eee9ab8d7 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/ViewAreaM.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/ViewAreaM.java @@ -11,13 +11,15 @@ @Mixin(ViewArea.class) public abstract class ViewAreaM { - @Shadow public SectionRenderDispatcher.RenderSection[] sections; + @Shadow + public SectionRenderDispatcher.RenderSection[] sections; - @Shadow protected abstract void setViewDistance(int i); + @Shadow + protected abstract void setViewDistance(int i); - @Inject(method = "createSections", at = @At("HEAD")) - private void skipAllocation(SectionRenderDispatcher sectionRenderDispatcher, CallbackInfo ci) { - // It's not possible to completely skip allocation since it would cause an error if repositionCamera is called - this.setViewDistance(0); - } -} + @Inject(method = "createSections", at = @At("HEAD")) + private void skipAllocation(SectionRenderDispatcher sectionRenderDispatcher, CallbackInfo ci) { + // It's not possible to completely skip allocation since it would cause an error if repositionCamera is called + this.setViewDistance(0); + } +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/chunk/VisibilitySetMixin.java b/src/main/java/net/vulkanmod/mixin/chunk/VisibilitySetMixin.java index 824abb3ba..354417023 100644 --- a/src/main/java/net/vulkanmod/mixin/chunk/VisibilitySetMixin.java +++ b/src/main/java/net/vulkanmod/mixin/chunk/VisibilitySetMixin.java @@ -9,7 +9,7 @@ @Mixin(VisibilitySet.class) public class VisibilitySetMixin implements VisibilitySetExtended { -// private int vis2 = 0; + // private int vis2 = 0; private long vis = 0; /** @@ -29,7 +29,7 @@ public void set(Direction dir1, Direction dir2, boolean p_112989_) { */ @Overwrite public void setAll(boolean bl) { - if(bl) this.vis = 0xFFFFFFFFFFFFFFFFL; + if (bl) this.vis = 0xFFFFFFFFFFFFFFFFL; } /** @@ -46,4 +46,4 @@ public boolean visibilityBetween(Direction dir1, Direction dir2) { public long getVisibility() { return vis; } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java b/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java deleted file mode 100644 index c3f49c08c..000000000 --- a/src/main/java/net/vulkanmod/mixin/compatibility/EffectInstanceM.java +++ /dev/null @@ -1,224 +0,0 @@ -package net.vulkanmod.mixin.compatibility; - -import com.google.gson.JsonObject; -import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.shaders.BlendMode; -import com.mojang.blaze3d.shaders.EffectProgram; -import com.mojang.blaze3d.shaders.Program; -import com.mojang.blaze3d.shaders.ProgramManager; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import net.minecraft.client.renderer.EffectInstance; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceProvider; -import net.vulkanmod.gl.VkGlProgram; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.shader.layout.Uniform; -import net.vulkanmod.vulkan.shader.descriptor.UBO; -import net.vulkanmod.vulkan.shader.converter.GlslConverter; -import net.vulkanmod.vulkan.util.MappedBuffer; -import org.apache.commons.io.IOUtils; -import org.lwjgl.opengl.GL30; -import org.lwjgl.system.MemoryUtil; -import org.spongepowered.asm.mixin.*; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.function.IntSupplier; -import java.util.function.Supplier; - -@Mixin(EffectInstance.class) -public class EffectInstanceM { - - @Shadow @Final private Map uniformMap; - @Shadow @Final private List uniforms; - - @Shadow private boolean dirty; - @Shadow private static EffectInstance lastAppliedEffect; - @Shadow @Final private BlendMode blend; - @Shadow private static int lastProgramId; - @Shadow @Final private int programId; - @Shadow @Final private List samplerLocations; - @Shadow @Final private List samplerNames; - @Shadow @Final private Map samplerMap; - - @Shadow @Final private String name; - - @Unique private static GraphicsPipeline lastPipeline; - @Unique private GraphicsPipeline pipeline; - - @Inject(method = "", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/EffectInstance;updateLocations()V", - shift = At.Shift.AFTER), - locals = LocalCapture.CAPTURE_FAILHARD - ) - private void inj(ResourceProvider resourceProvider, String string, CallbackInfo ci, ResourceLocation resourceLocation, Resource resource, Reader reader, JsonObject jsonObject, String string2, String string3) { - createShaders(resourceProvider, string2, string3); - } - - @Redirect(method = "", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/EffectInstance;getOrCreate(Lnet/minecraft/server/packs/resources/ResourceProvider;Lcom/mojang/blaze3d/shaders/Program$Type;Ljava/lang/String;)Lcom/mojang/blaze3d/shaders/EffectProgram;")) - private EffectProgram redirectShader(ResourceProvider resourceProvider, Program.Type type, String string) { - return null; - } - - /** - * @author - * @reason - */ - @Overwrite - public void close() { - for (com.mojang.blaze3d.shaders.Uniform uniform : this.uniforms) { - uniform.close(); - } - - this.pipeline.scheduleCleanUp(); - } - - private void createShaders(ResourceProvider resourceManager, String vertexShader, String fragShader) { - try { - String[] vshPathInfo = this.decompose(vertexShader, ':'); - ResourceLocation vshLocation = ResourceLocation.fromNamespaceAndPath(vshPathInfo[0], "shaders/program/" + vshPathInfo[1] + ".vsh"); - Resource resource = resourceManager.getResourceOrThrow(vshLocation); - InputStream inputStream = resource.open(); - String vshSrc = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - - String[] fshPathInfo = this.decompose(fragShader, ':'); - ResourceLocation fshLocation = ResourceLocation.fromNamespaceAndPath(fshPathInfo[0], "shaders/program/" + fshPathInfo[1] + ".fsh"); - resource = resourceManager.getResourceOrThrow(fshLocation); - inputStream = resource.open(); - String fshSrc = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - - GlslConverter converter = new GlslConverter(); - - converter.process(vshSrc, fshSrc); - UBO ubo = converter.createUBO(); - this.setUniformSuppliers(ubo); - - Pipeline.Builder builder = new Pipeline.Builder(DefaultVertexFormat.POSITION, this.name); - builder.setUniforms(Collections.singletonList(ubo), converter.getSamplerList()); - builder.compileShaders(this.name, converter.getVshConverted(), converter.getFshConverted()); - - this.pipeline = builder.createGraphicsPipeline(); - - VkGlProgram program = VkGlProgram.getProgram(this.programId); - program.bindPipeline(this.pipeline); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private void setUniformSuppliers(UBO ubo) { - - for(Uniform v_uniform : ubo.getUniforms()) { - com.mojang.blaze3d.shaders.Uniform uniform = this.uniformMap.get(v_uniform.getName()); - - Supplier supplier; - ByteBuffer byteBuffer; - - if (uniform.getType() <= 3) { - byteBuffer = MemoryUtil.memByteBuffer(uniform.getIntBuffer()); - } - else if (uniform.getType() <= 10) { - byteBuffer = MemoryUtil.memByteBuffer(uniform.getFloatBuffer()); - } - else { - throw new RuntimeException("out of bounds value for uniform " + uniform); - } - - MappedBuffer mappedBuffer = MappedBuffer.createFromBuffer(byteBuffer); - supplier = () -> mappedBuffer; - - v_uniform.setSupplier(supplier); - } - - } - - private String[] decompose(String string, char c) { - String[] strings = new String[]{"minecraft", string}; - int i = string.indexOf(c); - if (i >= 0) { - strings[1] = string.substring(i + 1); - if (i >= 1) { - strings[0] = string.substring(0, i); - } - } - - return strings; - } - - /** - * @author - * @reason - */ - @Overwrite - public void apply() { - this.dirty = false; - this.blend.apply(); - - ProgramManager.glUseProgram(this.programId); - - Renderer renderer = Renderer.getInstance(); - - if (this.pipeline != lastPipeline) { - renderer.bindGraphicsPipeline(pipeline); - lastPipeline = this.pipeline; - } - - for(int i = 0; i < this.samplerLocations.size(); ++i) { - String string = this.samplerNames.get(i); - IntSupplier intSupplier = this.samplerMap.get(string); - if (intSupplier != null) { - RenderSystem.activeTexture(GL30.GL_TEXTURE0 + i); - int j = intSupplier.getAsInt(); - if (j != -1) { - RenderSystem.bindTexture(j); - com.mojang.blaze3d.shaders.Uniform.uploadInteger(this.samplerLocations.get(i), i); - } - } - } - - for (com.mojang.blaze3d.shaders.Uniform uniform : this.uniforms) { - uniform.upload(); - } - - renderer.uploadAndBindUBOs(pipeline); - - } - - /** - * @author - * @reason - */ - @Overwrite - public void clear() { - RenderSystem.assertOnRenderThread(); - ProgramManager.glUseProgram(0); - lastProgramId = -1; - lastAppliedEffect = null; - lastPipeline = null; - - for(int i = 0; i < this.samplerLocations.size(); ++i) { - if (this.samplerMap.get(this.samplerNames.get(i)) != null) { - GlStateManager._activeTexture(GL30.GL_TEXTURE0 + i); - GlStateManager._bindTexture(0); - } - } - - } -} diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/PostChainM.java b/src/main/java/net/vulkanmod/mixin/compatibility/PostChainM.java deleted file mode 100644 index 885440c65..000000000 --- a/src/main/java/net/vulkanmod/mixin/compatibility/PostChainM.java +++ /dev/null @@ -1,291 +0,0 @@ -package net.vulkanmod.mixin.compatibility; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.systems.RenderSystem; -import net.minecraft.client.renderer.PostChain; -import net.minecraft.client.renderer.PostPass; -import net.minecraft.client.renderer.texture.AbstractTexture; -import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.ChainedJsonException; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.util.GsonHelper; -import net.vulkanmod.vulkan.Renderer; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; - -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -@Mixin(PostChain.class) -public abstract class PostChainM { - - @Shadow private int screenWidth; - @Shadow private int screenHeight; - - @Shadow @Final private Map customRenderTargets; - @Shadow @Final private RenderTarget screenTarget; - @Shadow @Final private List passes; - - @Shadow private float lastStamp; - @Shadow private float time; - - @Shadow public abstract void addTempTarget(String string, int i, int j); - @Shadow protected abstract void parseTargetNode(JsonElement jsonElement) throws ChainedJsonException; - @Shadow protected abstract void parseUniformNode(JsonElement jsonElement) throws ChainedJsonException; - -// /** -// * @author -// * @reason -// */ -// @Overwrite -// private void load(TextureManager textureManager, ResourceLocation resourceLocation) throws IOException, JsonSyntaxException { -// Resource resource = this.resourceManager.getResourceOrThrow(resourceLocation); -// -// try { -// Reader reader = resource.openAsReader(); -// -// try { -// JsonObject jsonObject = GsonHelper.parse(reader); -// JsonArray jsonArray; -// int i; -// JsonElement jsonElement; -// if (GsonHelper.isArrayNode(jsonObject, "targets")) { -// jsonArray = jsonObject.getAsJsonArray("targets"); -// i = 0; -// -// Iterator iterator; -// for(iterator = jsonArray.iterator(); iterator.hasNext(); ++i) { -// jsonElement = iterator.next(); -// -// try { -// this.parseTargetNode(jsonElement); -// } catch (Exception var14) { -// ChainedJsonException chainedJsonException = ChainedJsonException.forException(var14); -// chainedJsonException.prependJsonKey("targets[" + i + "]"); -// throw chainedJsonException; -// } -// } -// } -// -// if (GsonHelper.isArrayNode(jsonObject, "passes")) { -// jsonArray = jsonObject.getAsJsonArray("passes"); -// i = 0; -// -// Iterator iterator; -// for(iterator = jsonArray.iterator(); iterator.hasNext(); ++i) { -// jsonElement = iterator.next(); -// -// try { -// this.parsePassNode(textureManager, jsonElement); -// } catch (Exception var13) { -// ChainedJsonException chainedJsonException = ChainedJsonException.forException(var13); -// chainedJsonException.prependJsonKey("passes[" + i + "]"); -// throw chainedJsonException; -// } -// } -// } -// } catch (Throwable var15) { -// try { -// reader.close(); -// } catch (Throwable var12) { -// var15.addSuppressed(var12); -// } -// -// throw var15; -// } -// -// reader.close(); -// -// } catch (Exception var16) { -// ChainedJsonException chainedJsonException2 = ChainedJsonException.forException(var16); -// String var10001 = resourceLocation.getPath(); -// chainedJsonException2.setFilenameAndFlush(var10001 + " (" + resource.sourcePackId() + ")"); -// throw chainedJsonException2; -// } -// } - -// /** -// * @author -// * @reason -// */ -// @Overwrite -// private void parseTargetNode(JsonElement jsonElement) throws ChainedJsonException { -// if (GsonHelper.isStringValue(jsonElement)) { -// this.addTempTarget(jsonElement.getAsString(), this.screenWidth, this.screenHeight); -// } else { -// JsonObject jsonObject = GsonHelper.convertToJsonObject(jsonElement, "target"); -// String string = GsonHelper.getAsString(jsonObject, "name"); -// int i = GsonHelper.getAsInt(jsonObject, "width", this.screenWidth); -// int j = GsonHelper.getAsInt(jsonObject, "height", this.screenHeight); -// if (this.customRenderTargets.containsKey(string)) { -// throw new ChainedJsonException(string + " is already defined"); -// } -// -// this.addTempTarget(string, i, j); -// } -// -// } - -// /** -// * @author -// * @reason -// */ -// @Overwrite -// private void parsePassNode(TextureManager textureManager, JsonElement jsonElement) throws IOException { -// JsonObject jsonObject = GsonHelper.convertToJsonObject(jsonElement, "pass"); -// String string = GsonHelper.getAsString(jsonObject, "name"); -// String string2 = GsonHelper.getAsString(jsonObject, "intarget"); -// String string3 = GsonHelper.getAsString(jsonObject, "outtarget"); -// RenderTarget renderTarget = this.getRenderTarget(string2); -// RenderTarget renderTarget2 = this.getRenderTarget(string3); -// if (renderTarget == null) { -// throw new ChainedJsonException("Input target '" + string2 + "' does not exist"); -// } else if (renderTarget2 == null) { -// throw new ChainedJsonException("Output target '" + string3 + "' does not exist"); -// } else { -// PostPass postPass = this.addPass(string, renderTarget, renderTarget2); -// JsonArray jsonArray = GsonHelper.getAsJsonArray(jsonObject, "auxtargets", null); -// if (jsonArray != null) { -// int i = 0; -// -// for(Iterator var12 = jsonArray.iterator(); var12.hasNext(); ++i) { -// JsonElement jsonElement2 = (JsonElement)var12.next(); -// -// try { -// JsonObject jsonObject2 = GsonHelper.convertToJsonObject(jsonElement2, "auxtarget"); -// String string4 = GsonHelper.getAsString(jsonObject2, "name"); -// String string5 = GsonHelper.getAsString(jsonObject2, "id"); -// boolean bl; -// String string6; -// if (string5.endsWith(":depth")) { -// bl = true; -// string6 = string5.substring(0, string5.lastIndexOf(58)); -// } else { -// bl = false; -// string6 = string5; -// } -// -// RenderTarget renderTarget3 = this.getRenderTarget(string6); -// if (renderTarget3 == null) { -// if (bl) { -// throw new ChainedJsonException("Render target '" + string6 + "' can't be used as depth buffer"); -// } -// -// ResourceLocation resourceLocation = new ResourceLocation("textures/effect/" + string6 + ".png"); -// this.resourceManager.getResource(resourceLocation).orElseThrow(() -> { -// return new ChainedJsonException("Render target or texture '" + string6 + "' does not exist"); -// }); -// RenderSystem.setShaderTexture(0, resourceLocation); -// textureManager.bindForSetup(resourceLocation); -// AbstractTexture abstractTexture = textureManager.getTexture(resourceLocation); -// int j = GsonHelper.getAsInt(jsonObject2, "width"); -// int k = GsonHelper.getAsInt(jsonObject2, "height"); -// boolean bl2 = GsonHelper.getAsBoolean(jsonObject2, "bilinear"); -// if (bl2) { -// RenderSystem.texParameter(3553, 10241, 9729); -// RenderSystem.texParameter(3553, 10240, 9729); -// } else { -// RenderSystem.texParameter(3553, 10241, 9728); -// RenderSystem.texParameter(3553, 10240, 9728); -// } -// -// Objects.requireNonNull(abstractTexture); -// postPass.addAuxAsset(string4, abstractTexture::getId, j, k); -// } else if (bl) { -// Objects.requireNonNull(renderTarget3); -// postPass.addAuxAsset(string4, renderTarget3::getDepthTextureId, renderTarget3.width, renderTarget3.height); -// } else { -// Objects.requireNonNull(renderTarget3); -// postPass.addAuxAsset(string4, renderTarget3::getColorTextureId, renderTarget3.width, renderTarget3.height); -// } -// } catch (Exception e) { -// ChainedJsonException chainedJsonException = ChainedJsonException.forException(e); -// chainedJsonException.prependJsonKey("auxtargets[" + i + "]"); -// throw chainedJsonException; -// } -// } -// } -// -// JsonArray jsonArray2 = GsonHelper.getAsJsonArray(jsonObject, "uniforms", null); -// if (jsonArray2 != null) { -// int l = 0; -// -// for(Iterator var29 = jsonArray2.iterator(); var29.hasNext(); ++l) { -// JsonElement jsonElement3 = var29.next(); -// -// try { -// this.parseUniformNode(jsonElement3); -// } catch (Exception var25) { -// ChainedJsonException chainedJsonException2 = ChainedJsonException.forException(var25); -// chainedJsonException2.prependJsonKey("uniforms[" + l + "]"); -// throw chainedJsonException2; -// } -// } -// } -// -// } -// } -// -// private RenderTarget getRenderTarget(@Nullable String string) { -// if (string == null) { -// return null; -// } else { -// return string.equals("minecraft:main") ? this.screenTarget : this.customRenderTargets.get(string); -// } -// } -// -// public PostPass addPass(String string, RenderTarget renderTarget, RenderTarget renderTarget2) throws IOException { -// PostPass postPass = new PostPass(this.resourceManager, string, renderTarget, renderTarget2); -// this.passes.add(this.passes.size(), postPass); -// return postPass; -// } - - @Shadow protected abstract void setFilterMode(int i); - - /** - * @author - * @reason - */ - @Overwrite - public void process(float f) { - if (f < this.lastStamp) { - this.time += 1.0F - this.lastStamp; - this.time += f; - } else { - this.time += f - this.lastStamp; - } - - this.lastStamp = f; - - while(this.time > 20.0F) { - this.time -= 20.0F; - } - - int filterMode = 9728; - - for(PostPass postPass : this.passes) { - int passFilterMode = postPass.getFilterMode(); - if (filterMode != passFilterMode) { - this.setFilterMode(passFilterMode); - filterMode = passFilterMode; - } - - postPass.process(this.time / 20.0F); - } - - this.setFilterMode(9728); - - Renderer.resetViewport(); - } - -} diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java b/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java deleted file mode 100644 index 14c111690..000000000 --- a/src/main/java/net/vulkanmod/mixin/compatibility/PostPassM.java +++ /dev/null @@ -1,104 +0,0 @@ -package net.vulkanmod.mixin.compatibility; - -import com.mojang.blaze3d.pipeline.MainTarget; -import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.*; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.EffectInstance; -import net.minecraft.client.renderer.PostPass; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.VRenderSystem; -import net.vulkanmod.vulkan.util.DrawUtil; -import org.joml.Matrix4f; -import org.lwjgl.opengl.GL11; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; - -import java.util.List; -import java.util.Objects; -import java.util.function.IntSupplier; - -@Mixin(PostPass.class) -public class PostPassM { - - @Shadow @Final public RenderTarget inTarget; - - @Shadow @Final public RenderTarget outTarget; - - @Shadow @Final private EffectInstance effect; - - @Shadow @Final private List auxAssets; - - @Shadow @Final private List auxNames; - - @Shadow @Final private List auxWidths; - - @Shadow @Final private List auxHeights; - - @Shadow private Matrix4f shaderOrthoMatrix; - - /** - * @author - * @reason - */ - @Overwrite - public void process(float f) { - this.inTarget.unbindWrite(); - float g = (float)this.outTarget.width; - float h = (float)this.outTarget.height; - RenderSystem.viewport(0, 0, (int)g, (int)h); - - Objects.requireNonNull(this.inTarget); - this.effect.setSampler("DiffuseSampler", this.inTarget::getColorTextureId); - - if(this.inTarget instanceof MainTarget) - this.inTarget.bindRead(); - - for(int i = 0; i < this.auxAssets.size(); ++i) { - this.effect.setSampler(this.auxNames.get(i), this.auxAssets.get(i)); - this.effect.safeGetUniform("AuxSize" + i).set((float) this.auxWidths.get(i), (float) this.auxHeights.get(i)); - } - - this.effect.safeGetUniform("ProjMat").set(this.shaderOrthoMatrix); - this.effect.safeGetUniform("InSize").set((float)this.inTarget.width, (float)this.inTarget.height); - this.effect.safeGetUniform("OutSize").set(g, h); - this.effect.safeGetUniform("Time").set(f); - Minecraft minecraft = Minecraft.getInstance(); - this.effect.safeGetUniform("ScreenSize").set((float)minecraft.getWindow().getWidth(), (float)minecraft.getWindow().getHeight()); - - this.outTarget.clear(Minecraft.ON_OSX); - this.outTarget.bindWrite(false); - - VRenderSystem.disableCull(); - VRenderSystem.depthFunc(519); - VRenderSystem.setPrimitiveTopologyGL(GL11.GL_TRIANGLES); - - Renderer.setInvertedViewport(0, 0, this.outTarget.width, this.outTarget.height); - Renderer.resetScissor(); - - this.effect.apply(); - - BufferBuilder bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION); - bufferBuilder.addVertex(0.0f, 0.0f, 500.0f); - bufferBuilder.addVertex(g, 0.0f, 500.0f); - bufferBuilder.addVertex(g, h, 500.0f); - bufferBuilder.addVertex(0.0f, h, 500.0f); - BufferUploader.draw(bufferBuilder.buildOrThrow()); - RenderSystem.depthFunc(515); - - this.effect.clear(); - this.outTarget.unbindWrite(); - this.inTarget.unbindRead(); - - for (Object object : this.auxAssets) { - if (object instanceof RenderTarget) { - ((RenderTarget) object).unbindRead(); - } - } - - VRenderSystem.enableCull(); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/ProgramM.java b/src/main/java/net/vulkanmod/mixin/compatibility/ProgramM.java deleted file mode 100644 index 7771c43f9..000000000 --- a/src/main/java/net/vulkanmod/mixin/compatibility/ProgramM.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.vulkanmod.mixin.compatibility; - -import com.mojang.blaze3d.preprocessor.GlslPreprocessor; -import com.mojang.blaze3d.shaders.Program; -import net.vulkanmod.gl.GlUtil; -import net.vulkanmod.vulkan.shader.SPIRVUtils; -import org.apache.commons.io.IOUtils; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; - -@Mixin(Program.class) -public class ProgramM { - - /** - * @author - * @reason - */ - @Overwrite - public static int compileShaderInternal(Program.Type type, String string, InputStream inputStream, String string2, GlslPreprocessor glslPreprocessor) throws IOException { - String string3 = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - if (string3 == null) { - throw new IOException("Could not load program " + type.getName()); - } else { -// int i = GlStateManager.glCreateShader(type.getGlType()); -// GlStateManager.glShaderSource(i, glslPreprocessor.process(string3)); -// GlStateManager.glCompileShader(i); -// if (GlStateManager.glGetShaderi(i, 35713) == 0) { -// String string4 = StringUtils.trim(GlStateManager.glGetShaderInfoLog(i, 32768)); -// throw new IOException("Couldn't compile " + type.getName() + " program (" + string2 + ", " + string + ") : " + string4); -// } else { -// return i; -// } - - //TODO maybe not needed? - glslPreprocessor.process(string3); - SPIRVUtils.compileShader(string2 + ":" + string, string3, GlUtil.extToShaderKind(type.getExtension())); - } - return 0; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java b/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java deleted file mode 100644 index 588e7d167..000000000 --- a/src/main/java/net/vulkanmod/mixin/compatibility/UniformM.java +++ /dev/null @@ -1,64 +0,0 @@ -package net.vulkanmod.mixin.compatibility; - -import com.mojang.blaze3d.shaders.Shader; -import com.mojang.blaze3d.shaders.Uniform; -import net.vulkanmod.gl.VkGlProgram; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.shader.Pipeline; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(Uniform.class) -public class UniformM { - - @Shadow @Final private Shader parent; - - /** - * @author - * @reason - */ - @Overwrite - public static int glGetUniformLocation(int i, CharSequence charSequence) { - //TODO - return 1; - } - - /** - * @author - * @reason - */ - @Overwrite - public static int glGetAttribLocation(int i, CharSequence charSequence) { - return 0; - } - - @Inject(method = "upload", at = @At("HEAD"), cancellable = true) - public void redirectUpload(CallbackInfo ci) { - Renderer renderer = Renderer.getInstance(); - Pipeline boundPipeline = renderer.getBoundPipeline(); - - ci.cancel(); - - VkGlProgram program = VkGlProgram.getBoundProgram(); - - if (program == null) { - return; - } - - // Update descriptors only if the pipeline has already been bound - Pipeline pipeline = program.getPipeline(); - if (boundPipeline == pipeline) { - renderer.uploadAndBindUBOs(boundPipeline); - } - } - - @Inject(method = "uploadInteger", at = @At("HEAD"), cancellable = true) - private static void cancelUploadInteger(int i, int j, CallbackInfo ci) { - ci.cancel(); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java index e004b0aa2..7d8ca6d13 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL11M.java @@ -3,13 +3,13 @@ import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; +import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; import org.lwjgl.system.MemoryUtil; import org.lwjgl.system.NativeType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; -import org.jetbrains.annotations.Nullable; import java.nio.ByteBuffer; import java.nio.IntBuffer; @@ -306,7 +306,6 @@ public static void glBlendFunc(@NativeType("GLenum") int sfactor, @NativeType("G } - /** * @author * @reason @@ -315,4 +314,4 @@ public static void glBlendFunc(@NativeType("GLenum") int sfactor, @NativeType("G public static void glPolygonOffset(@NativeType("GLfloat") float factor, @NativeType("GLfloat") float units) { VRenderSystem.polygonOffset(factor, units); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL14M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL14M.java index 6d6781524..e7566aa64 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL14M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL14M.java @@ -2,7 +2,6 @@ import net.vulkanmod.vulkan.VRenderSystem; import org.lwjgl.opengl.GL14; -import org.lwjgl.opengl.GL14C; import org.lwjgl.system.NativeType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -18,4 +17,4 @@ public class GL14M { public static void glBlendFuncSeparate(@NativeType("GLenum") int sfactorRGB, @NativeType("GLenum") int dfactorRGB, @NativeType("GLenum") int sfactorAlpha, @NativeType("GLenum") int dfactorAlpha) { VRenderSystem.blendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL15M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL15M.java index 65cc49840..03c47f592 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL15M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL15M.java @@ -89,4 +89,4 @@ public static void glDeleteBuffers(int i) { public static void glDeleteBuffers(@NativeType("GLuint const *") IntBuffer buffers) { VkGlBuffer.glDeleteBuffers(buffers); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL30M.java b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL30M.java index 0823849ec..7f62ae74a 100644 --- a/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL30M.java +++ b/src/main/java/net/vulkanmod/mixin/compatibility/gl/GL30M.java @@ -123,4 +123,4 @@ public static void glRenderbufferStorage(@NativeType("GLenum") int target, @Nati public static void glDeleteRenderbuffers(@NativeType("GLuint const *") int renderbuffer) { VkGlRenderbuffer.deleteRenderbuffer(renderbuffer); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/debug/DebugScreenOverlayM.java b/src/main/java/net/vulkanmod/mixin/debug/DebugScreenOverlayM.java index da44e8b84..cdb4a6f3d 100644 --- a/src/main/java/net/vulkanmod/mixin/debug/DebugScreenOverlayM.java +++ b/src/main/java/net/vulkanmod/mixin/debug/DebugScreenOverlayM.java @@ -27,16 +27,15 @@ public abstract class DebugScreenOverlayM { @Shadow @Final private Minecraft minecraft; + @Shadow + @Final + private Font font; @Shadow private static long bytesToMegabytes(long bytes) { return 0; } - @Shadow - @Final - private Font font; - @Shadow protected abstract List getGameInformation(); @@ -77,4 +76,4 @@ private ArrayList redirectList(Object[] elements) { private long getOffHeapMemory() { return bytesToMegabytes(ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed()); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/debug/GlDebugInfoM.java b/src/main/java/net/vulkanmod/mixin/debug/GlDebugInfoM.java deleted file mode 100644 index 10986a42a..000000000 --- a/src/main/java/net/vulkanmod/mixin/debug/GlDebugInfoM.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.vulkanmod.mixin.debug; - -import com.mojang.blaze3d.platform.GlUtil; -import net.vulkanmod.vulkan.SystemInfo; -import net.vulkanmod.vulkan.Vulkan; -import net.vulkanmod.vulkan.device.Device; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -@Mixin(GlUtil.class) -public class GlDebugInfoM { - - /** - * @author - */ - @Overwrite - public static String getVendor() { - return Vulkan.getDevice() != null ? Vulkan.getDevice().vendorIdString : "n/a"; - } - - /** - * @author - */ - @Overwrite - public static String getRenderer() { - return Vulkan.getDevice() != null ? Vulkan.getDevice().deviceName : "n/a"; - } - - /** - * @author - */ - @Overwrite - public static String getOpenGLVersion() { - return Vulkan.getDevice() != null ? Vulkan.getDevice().driverVersion : "n/a"; - } - - /** - * @author - */ - @Overwrite - public static String getCpuInfo() { - return SystemInfo.cpuInfo; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/debug/KeyboardHandlerM.java b/src/main/java/net/vulkanmod/mixin/debug/KeyboardHandlerM.java index 67330cece..925861aab 100644 --- a/src/main/java/net/vulkanmod/mixin/debug/KeyboardHandlerM.java +++ b/src/main/java/net/vulkanmod/mixin/debug/KeyboardHandlerM.java @@ -3,6 +3,7 @@ import com.mojang.blaze3d.platform.InputConstants; import net.minecraft.client.KeyboardHandler; import net.minecraft.client.Minecraft; +import net.minecraft.client.input.KeyEvent; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -12,15 +13,17 @@ @Mixin(KeyboardHandler.class) public abstract class KeyboardHandlerM { - @Shadow protected abstract boolean handleChunkDebugKeys(int i); + @Shadow + private boolean handledDebugKey; - @Shadow private boolean handledDebugKey; + @Shadow + protected abstract boolean handleChunkDebugKeys(KeyEvent keyEvent); - @Inject(method = "keyPress", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/InputConstants;isKeyDown(JI)Z", ordinal = 0, shift = At.Shift.AFTER)) - private void chunkDebug(long window, int key, int scancode, int action, int mods, CallbackInfo ci) { + @Inject(method = "keyPress", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/InputConstants;isKeyDown(Lcom/mojang/blaze3d/platform/Window;I)Z", ordinal = 0, shift = At.Shift.AFTER), remap = false) + private void chunkDebug(long window, int action, KeyEvent keyEvent, CallbackInfo ci) { // GLFW key 296 -> F7 // U -> Capture frustum - this.handledDebugKey |= InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), 296) - && this.handleChunkDebugKeys(key); + this.handledDebugKey |= InputConstants.isKeyDown(Minecraft.getInstance().getWindow(), 296) + && this.handleChunkDebugKeys(keyEvent); } } diff --git a/src/main/java/net/vulkanmod/mixin/debug/crash_report/SystemReportM.java b/src/main/java/net/vulkanmod/mixin/debug/crash_report/SystemReportM.java index 621a389a7..7a2d36f2c 100644 --- a/src/main/java/net/vulkanmod/mixin/debug/crash_report/SystemReportM.java +++ b/src/main/java/net/vulkanmod/mixin/debug/crash_report/SystemReportM.java @@ -10,9 +10,9 @@ @Mixin(SystemReport.class) public class SystemReportM { - @Inject(method = "appendToCrashReportString", at = @At("RETURN")) - private void addVulkanDevicesInfo(StringBuilder stringBuilder, CallbackInfo ci) { - stringBuilder.append("\n\n -- VulkanMod Device Report --"); - stringBuilder.append(DeviceManager.getAvailableDevicesInfo()); - } + @Inject(method = "appendToCrashReportString", at = @At("RETURN")) + private void addVulkanDevicesInfo(StringBuilder stringBuilder, CallbackInfo ci) { + stringBuilder.append("\n\n -- VulkanMod Device Report --"); + stringBuilder.append(DeviceManager.getAvailableDevicesInfo()); + } } diff --git a/src/main/java/net/vulkanmod/mixin/matrix/Matrix4fM.java b/src/main/java/net/vulkanmod/mixin/matrix/Matrix4fM.java index 071a62fd6..e7b042537 100644 --- a/src/main/java/net/vulkanmod/mixin/matrix/Matrix4fM.java +++ b/src/main/java/net/vulkanmod/mixin/matrix/Matrix4fM.java @@ -8,8 +8,11 @@ @Mixin(Matrix4f.class) public abstract class Matrix4fM { - @Shadow public abstract Matrix4f perspective(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne); - @Shadow public abstract Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne); + @Shadow + public abstract Matrix4f perspective(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne); + + @Shadow + public abstract Matrix4f ortho(float left, float right, float bottom, float top, float zNear, float zFar, boolean zZeroToOne); /** * @author @@ -46,4 +49,4 @@ public Matrix4f perspective(float fovy, float aspect, float zNear, float zFar) { public Matrix4f setPerspective(float fovy, float aspect, float zNear, float zFar) { return new Matrix4f().setPerspective(fovy, aspect, zNear, zFar, true); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/matrix/PoseAccessor.java b/src/main/java/net/vulkanmod/mixin/matrix/PoseAccessor.java index cc2acf61a..0f1e2bcb3 100644 --- a/src/main/java/net/vulkanmod/mixin/matrix/PoseAccessor.java +++ b/src/main/java/net/vulkanmod/mixin/matrix/PoseAccessor.java @@ -9,4 +9,4 @@ public interface PoseAccessor { @Accessor("trustedNormals") boolean trustedNormals(); -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/profiling/ClientMetricsSamplersProviderMixin.java b/src/main/java/net/vulkanmod/mixin/profiling/ClientMetricsSamplersProviderMixin.java deleted file mode 100644 index d5067ecfa..000000000 --- a/src/main/java/net/vulkanmod/mixin/profiling/ClientMetricsSamplersProviderMixin.java +++ /dev/null @@ -1,19 +0,0 @@ -// In a new file, e.g., ClientMetricsSamplersProviderMixin.java -package net.vulkanmod.mixin.profiling; // Or an appropriate package - -import com.mojang.blaze3d.systems.TimerQuery; -import net.minecraft.client.profiling.ClientMetricsSamplersProvider; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -import java.util.Optional; - -@Mixin(ClientMetricsSamplersProvider.class) -public class ClientMetricsSamplersProviderMixin { - - @Redirect(method = "registerStaticSamplers", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/TimerQuery;getInstance()Ljava/util/Optional;")) - private Optional preventTimerQuery() { - return Optional.empty(); - } -} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/profiling/GuiMixin.java b/src/main/java/net/vulkanmod/mixin/profiling/GuiMixin.java index 1fd1ede71..d84f18c0b 100644 --- a/src/main/java/net/vulkanmod/mixin/profiling/GuiMixin.java +++ b/src/main/java/net/vulkanmod/mixin/profiling/GuiMixin.java @@ -5,7 +5,6 @@ import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.DebugScreenOverlay; -import net.minecraft.client.renderer.entity.ItemRenderer; import net.vulkanmod.render.profiling.ProfilerOverlay; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -17,7 +16,9 @@ @Mixin(Gui.class) public class GuiMixin { - @Shadow @Final private DebugScreenOverlay debugOverlay; + @Shadow + @Final + private DebugScreenOverlay debugOverlay; @Inject(method = "", at = @At("RETURN")) private void createProfilerOverlay(Minecraft minecraft, CallbackInfo ci) { @@ -26,7 +27,7 @@ private void createProfilerOverlay(Minecraft minecraft, CallbackInfo ci) { @Inject(method = "render", at = @At(value = "RETURN")) private void renderProfilerOverlay(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { - if(ProfilerOverlay.shouldRender && !this.debugOverlay.showDebugScreen()) + if (ProfilerOverlay.shouldRender && !this.debugOverlay.showDebugScreen()) ProfilerOverlay.INSTANCE.render(guiGraphics); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/profiling/KeyboardHandlerM.java b/src/main/java/net/vulkanmod/mixin/profiling/KeyboardHandlerM.java index 242ce3060..02faeaf59 100644 --- a/src/main/java/net/vulkanmod/mixin/profiling/KeyboardHandlerM.java +++ b/src/main/java/net/vulkanmod/mixin/profiling/KeyboardHandlerM.java @@ -3,6 +3,7 @@ import com.mojang.blaze3d.platform.InputConstants; import net.minecraft.client.KeyboardHandler; import net.minecraft.client.Minecraft; +import net.minecraft.client.input.KeyEvent; import net.vulkanmod.render.profiling.BuildTimeProfiler; import net.vulkanmod.render.profiling.ProfilerOverlay; import org.lwjgl.glfw.GLFW; @@ -17,15 +18,14 @@ public class KeyboardHandlerM { @Inject(method = "keyPress", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/KeyMapping;set(Lcom/mojang/blaze3d/platform/InputConstants$Key;Z)V", ordinal = 0, shift = At.Shift.AFTER)) - private void injOverlayToggle(long window, int key, int scancode, int action, int mods, CallbackInfo ci) { - if(InputConstants.isKeyDown(Minecraft.getInstance().getWindow().getWindow(), GLFW.GLFW_KEY_LEFT_ALT)) { - switch (key) { + private void injOverlayToggle(long window, int action, KeyEvent keyEvent, CallbackInfo ci) { + if (InputConstants.isKeyDown(Minecraft.getInstance().getWindow(), GLFW.GLFW_KEY_LEFT_ALT)) { + switch (keyEvent.key()) { case GLFW.GLFW_KEY_F8 -> ProfilerOverlay.toggle(); case GLFW.GLFW_KEY_F10 -> BuildTimeProfiler.startBench(); } - } - else if(ProfilerOverlay.shouldRender) { - ProfilerOverlay.onKeyPress(key); + } else if (ProfilerOverlay.shouldRender) { + ProfilerOverlay.onKeyPress(keyEvent.key()); } } } diff --git a/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java b/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java index d1b69098c..5fa8c5c9d 100644 --- a/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java +++ b/src/main/java/net/vulkanmod/mixin/profiling/LevelRendererMixin.java @@ -100,4 +100,4 @@ private void profilerTerrain4_1(DeltaTracker deltaTracker, boolean bl, Camera ca Profiler profiler = Profiler.getMainProfiler(); profiler.pop(); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java b/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java deleted file mode 100644 index c270e749c..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/BufferUploaderM.java +++ /dev/null @@ -1,74 +0,0 @@ -package net.vulkanmod.mixin.render; - -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.BufferUploader; -import com.mojang.blaze3d.vertex.MeshData; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.ShaderInstance; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.VRenderSystem; - -import net.vulkanmod.vulkan.shader.Pipeline; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -@Mixin(BufferUploader.class) -public abstract class BufferUploaderM { - - /** - * @author - */ - @Overwrite - public static void reset() {} - - /** - * @author - */ - @Overwrite - public static void drawWithShader(MeshData meshData) { - RenderSystem.assertOnRenderThread(); - - MeshData.DrawState parameters = meshData.drawState(); - if (parameters.vertexCount() > 0) { - ShaderInstance shaderInstance = RenderSystem.getShader(); - - // Prevent drawing if formats don't match to avoid disturbing visual bugs - if (shaderInstance.getVertexFormat() != parameters.format()) { - meshData.close(); - return; - } - - VRenderSystem.setPrimitiveTopologyGL(parameters.mode().asGLMode); - - // Used to update legacy shader uniforms - // TODO it would be faster to allocate a buffer from stack and set all values - shaderInstance.setDefaultUniforms(VertexFormat.Mode.QUADS, RenderSystem.getModelViewMatrix(), - RenderSystem.getProjectionMatrix(), Minecraft.getInstance().getWindow()); - shaderInstance.apply(); - - Renderer.getDrawer().draw(meshData.vertexBuffer(), meshData.indexBuffer(), parameters.mode(), parameters.format(), parameters.vertexCount()); - } - - meshData.close(); - } - - /** - * @author - */ - @Overwrite - public static void draw(MeshData meshData) { - MeshData.DrawState parameters = meshData.drawState(); - - if (parameters.vertexCount() > 0) { - Renderer renderer = Renderer.getInstance(); - Pipeline pipeline = renderer.getBoundPipeline(); - renderer.uploadAndBindUBOs(pipeline); - - Renderer.getDrawer().draw(meshData.vertexBuffer(), null, parameters.mode(), parameters.format(), parameters.vertexCount()); - } - - meshData.close(); - } - -} diff --git a/src/main/java/net/vulkanmod/mixin/render/DirectStateAccessCoreMixin.java b/src/main/java/net/vulkanmod/mixin/render/DirectStateAccessCoreMixin.java new file mode 100644 index 000000000..be8af1ae7 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/DirectStateAccessCoreMixin.java @@ -0,0 +1,61 @@ +package net.vulkanmod.mixin.render; + +import net.vulkanmod.gl.VkGlFramebuffer; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL30; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; + +@Mixin(targets = "com.mojang.blaze3d.opengl.DirectStateAccess$Core", remap = false) +public abstract class DirectStateAccessCoreMixin { + + /** + * Route framebuffer creation through the Vulkan compatibility layer so IDs are tracked. + */ + @Overwrite(remap = false) + public int createFrameBufferObject() { + return VkGlFramebuffer.genFramebufferId(); + } + + /** + * Attach Mojang's textures to our emulated framebuffer and optionally bind it. + */ + @Overwrite(remap = false) + public void bindFrameBufferTextures(int framebuffer, int colorTexture, int depthTexture, int level, int bindTarget) { + if (framebuffer == 0) { + VkGlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, 0); + return; + } + + VkGlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer); + + if (colorTexture != 0) { + VkGlFramebuffer.framebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, colorTexture, level); + } + + if (depthTexture != 0) { + VkGlFramebuffer.framebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, depthTexture, level); + } + + if (bindTarget != 0) { + VkGlFramebuffer.bindFramebuffer(bindTarget, framebuffer); + } else { + VkGlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, 0); + } + } + + /** + * Forward blits through the Vulkan framebuffer bridge. + */ + @Overwrite(remap = false) + public void blitFrameBuffers(int srcFramebuffer, int dstFramebuffer, + int srcX0, int srcY0, int srcX1, int srcY1, + int dstX0, int dstY0, int dstX1, int dstY1, + int mask, int filter) { + VkGlFramebuffer.bindFramebuffer(GL30.GL_READ_FRAMEBUFFER, srcFramebuffer); + VkGlFramebuffer.bindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, dstFramebuffer); + VkGlFramebuffer.glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); + VkGlFramebuffer.bindFramebuffer(GL30.GL_READ_FRAMEBUFFER, 0); + VkGlFramebuffer.bindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, 0); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/DirectStateAccessEmulatedMixin.java b/src/main/java/net/vulkanmod/mixin/render/DirectStateAccessEmulatedMixin.java new file mode 100644 index 000000000..a08c4bd61 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/DirectStateAccessEmulatedMixin.java @@ -0,0 +1,52 @@ +package net.vulkanmod.mixin.render; + +import net.vulkanmod.gl.VkGlFramebuffer; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL30; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; + +@Mixin(targets = "com.mojang.blaze3d.opengl.DirectStateAccess$Emulated", remap = false) +public abstract class DirectStateAccessEmulatedMixin { + + @Overwrite(remap = false) + public int createFrameBufferObject() { + return VkGlFramebuffer.genFramebufferId(); + } + + @Overwrite(remap = false) + public void bindFrameBufferTextures(int framebuffer, int colorTexture, int depthTexture, int level, int bindTarget) { + if (framebuffer == 0) { + VkGlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, 0); + return; + } + + VkGlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer); + + if (colorTexture != 0) { + VkGlFramebuffer.framebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, colorTexture, level); + } + + if (depthTexture != 0) { + VkGlFramebuffer.framebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, depthTexture, level); + } + + if (bindTarget != 0) { + VkGlFramebuffer.bindFramebuffer(bindTarget, framebuffer); + } else { + VkGlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, 0); + } + } + + @Overwrite(remap = false) + public void blitFrameBuffers(int srcFramebuffer, int dstFramebuffer, + int srcX0, int srcY0, int srcX1, int srcY1, + int dstX0, int dstY0, int dstX1, int dstY1, + int mask, int filter) { + VkGlFramebuffer.bindFramebuffer(GL30.GL_READ_FRAMEBUFFER, srcFramebuffer); + VkGlFramebuffer.bindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, dstFramebuffer); + VkGlFramebuffer.glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); + VkGlFramebuffer.bindFramebuffer(GL30.GL_READ_FRAMEBUFFER, 0); + VkGlFramebuffer.bindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, 0); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/DynamicUniformsMixin.java b/src/main/java/net/vulkanmod/mixin/render/DynamicUniformsMixin.java new file mode 100644 index 000000000..f2c6d8b24 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/DynamicUniformsMixin.java @@ -0,0 +1,27 @@ +package net.vulkanmod.mixin.render; + +import com.mojang.blaze3d.buffers.GpuBufferSlice; +import net.minecraft.client.renderer.DynamicUniforms; +import net.vulkanmod.vulkan.VRenderSystem; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.joml.Vector3fc; +import org.joml.Vector4fc; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(DynamicUniforms.class) +public class DynamicUniformsMixin { + + @Inject(method = "writeTransform", at = @At("HEAD")) + private void captureTransform(Matrix4fc modelView, Vector4fc color, Vector3fc modelOffset, Matrix4fc textureMatrix, float lineWidth, CallbackInfoReturnable cir) { + VRenderSystem.applyModelViewMatrix(new Matrix4f(modelView)); + VRenderSystem.setShaderColor(color.x(), color.y(), color.z(), color.w()); + VRenderSystem.setModelOffset(modelOffset.x(), modelOffset.y(), modelOffset.z()); + VRenderSystem.setTextureMatrix(new Matrix4f(textureMatrix)); + VRenderSystem.setLineWidth(lineWidth); + VRenderSystem.calculateMVP(); + } +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/render/FogRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/FogRendererMixin.java new file mode 100644 index 000000000..94f1cb69e --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/FogRendererMixin.java @@ -0,0 +1,25 @@ +package net.vulkanmod.mixin.render; + +import net.minecraft.client.renderer.fog.FogRenderer; +import net.vulkanmod.vulkan.VRenderSystem; +import org.joml.Vector4f; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.nio.ByteBuffer; + +@Mixin(FogRenderer.class) +public abstract class FogRendererMixin { + + @Inject(method = "updateBuffer", at = @At("TAIL")) + private void vulkanmod$captureFog(ByteBuffer buffer, int offset, Vector4f color, + float environmentalStart, float environmentalEnd, + float renderStart, float renderEnd, + float skyEnd, float cloudEnd, CallbackInfo ci) { + VRenderSystem.setShaderFogColor(color.x, color.y, color.z, color.w); + VRenderSystem.setFogParameters(environmentalStart, renderStart, environmentalEnd, renderEnd, skyEnd, cloudEnd); + VRenderSystem.setFogShapeIndex(0); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java deleted file mode 100644 index d516895d6..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/GameRendererMixin.java +++ /dev/null @@ -1,89 +0,0 @@ -package net.vulkanmod.mixin.render; - -import com.google.common.collect.ImmutableList; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.ShaderInstance; -import net.minecraft.server.packs.resources.ResourceProvider; -import net.vulkanmod.vulkan.memory.MemoryManager; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; - -import java.io.IOException; -import java.util.Map; - -@Mixin(GameRenderer.class) -public abstract class GameRendererMixin { - - @Shadow @Final private Map shaders; - - @Shadow private @Nullable static ShaderInstance positionShader; - @Shadow private @Nullable static ShaderInstance positionColorShader; - @Shadow private @Nullable static ShaderInstance positionTexShader; - @Shadow private @Nullable static ShaderInstance positionTexColorShader; - @Shadow private @Nullable static ShaderInstance rendertypeTextShader; - @Shadow private static @Nullable ShaderInstance rendertypeGuiShader; - @Shadow private static @Nullable ShaderInstance rendertypeGuiOverlayShader; - - @Shadow public ShaderInstance blitShader; - - @Shadow protected abstract ShaderInstance preloadShader(ResourceProvider resourceProvider, String string, VertexFormat vertexFormat); - - @Shadow public abstract float getRenderDistance(); - - /** - * @author - * @reason - */ - @Overwrite - private void shutdownShaders() { - RenderSystem.assertOnRenderThread(); - - final var clearList = ImmutableList.copyOf(this.shaders.values()); - MemoryManager.getInstance().addFrameOp(() -> clearList.forEach((ShaderInstance::close))); - - this.shaders.clear(); - } - - /** - * @author - * @reason - */ - @Overwrite - public void preloadUiShader(ResourceProvider resourceProvider) { - if (this.blitShader != null) { - throw new RuntimeException("Blit shader already preloaded"); - } else { - try { - this.blitShader = new ShaderInstance(resourceProvider, "blit_screen", DefaultVertexFormat.POSITION_TEX); - } catch (IOException var3) { - throw new RuntimeException("could not preload blit shader", var3); - } - - positionShader = this.preloadShader(resourceProvider, "position", DefaultVertexFormat.POSITION); - positionColorShader = this.preloadShader(resourceProvider, "position_color", DefaultVertexFormat.POSITION_COLOR); - positionTexShader = this.preloadShader(resourceProvider, "position_tex", DefaultVertexFormat.POSITION_TEX); - positionTexColorShader = this.preloadShader(resourceProvider, "position_tex_color", DefaultVertexFormat.POSITION_TEX_COLOR); - rendertypeTextShader = this.preloadShader(resourceProvider, "rendertype_text", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP); - - rendertypeGuiShader = positionColorShader; - rendertypeGuiOverlayShader = positionColorShader; - } - } - - /** - * @author - * @reason - */ - @Overwrite - public float getDepthFar() { -// return this.getRenderDistance() * 4.0F; - return Float.POSITIVE_INFINITY; - } - -} diff --git a/src/main/java/net/vulkanmod/mixin/render/GlDeviceMixin.java b/src/main/java/net/vulkanmod/mixin/render/GlDeviceMixin.java new file mode 100644 index 000000000..d94e7c9b8 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/GlDeviceMixin.java @@ -0,0 +1,118 @@ +package net.vulkanmod.mixin.render; + +import com.mojang.blaze3d.opengl.GlDevice; +import com.mojang.blaze3d.opengl.GlProgram; +import com.mojang.blaze3d.opengl.GlRenderPipeline; +import com.mojang.blaze3d.opengl.GlShaderModule; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.preprocessor.GlslPreprocessor; +import com.mojang.blaze3d.shaders.ShaderType; +import net.minecraft.resources.ResourceLocation; +import net.vulkanmod.gl.VkGlProgram; +import net.vulkanmod.interfaces.GlShaderModuleExt; +import net.vulkanmod.mixin.render.accessor.ShaderCompilationKeyAccessor; +import net.vulkanmod.render.pipeline.VulkanPipelineCompiler; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.*; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Coerce; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.function.BiFunction; + +@Mixin(value = GlDevice.class, remap = false) +public abstract class GlDeviceMixin { + + @Unique + private static final String VULKANMOD_SHADER_ERROR = "[VulkanMod] Missing GLSL source for shader %s (%s)"; + @Shadow + private BiFunction defaultShaderSource; + @Shadow + @Final + @Mutable + private int uniformOffsetAlignment; + + @Inject(method = "getMaxSupportedTextureSize", at = @At("HEAD"), cancellable = true) + private static void vulkanmod$maxTextureSize(CallbackInfoReturnable cir) { + cir.setReturnValue(16384); + } + + @Shadow + protected abstract GlShaderModule getOrCompileShader(ResourceLocation id, ShaderType type, + net.minecraft.client.renderer.ShaderDefines defines, + BiFunction shaderSourceGetter); + + @Inject( + method = "compileShader(Lcom/mojang/blaze3d/opengl/GlDevice$ShaderCompilationKey;Ljava/util/function/BiFunction;)Lcom/mojang/blaze3d/opengl/GlShaderModule;", + at = @At("HEAD"), + cancellable = true + ) + private void vulkanmod$compileShader(@Coerce Object keyObject, + BiFunction sourceGetter, + CallbackInfoReturnable cir) { + ShaderCompilationKeyAccessor key = (ShaderCompilationKeyAccessor) keyObject; + + BiFunction getter = sourceGetter != null ? sourceGetter : this.defaultShaderSource; + + ResourceLocation id = key.vulkanmod$getId(); + ShaderType type = key.vulkanmod$getType(); + + String rawSource = getter.apply(id, type); + if (rawSource == null) { + throw new IllegalStateException(VULKANMOD_SHADER_ERROR.formatted(type.getName(), id)); + } + + String processedSource = GlslPreprocessor.injectDefines(rawSource, key.vulkanmod$getDefines()); + + GlShaderModule module = new GlShaderModule(-1, id, type); + ((GlShaderModuleExt) module).vulkanmod$setProcessedSource(processedSource); + cir.setReturnValue(module); + cir.cancel(); + } + + @Inject( + method = "compilePipeline(Lcom/mojang/blaze3d/pipeline/RenderPipeline;Ljava/util/function/BiFunction;)Lcom/mojang/blaze3d/opengl/GlRenderPipeline;", + at = @At("HEAD"), + cancellable = true + ) + private void vulkanmod$compilePipeline(RenderPipeline pipeline, + @Nullable BiFunction sourceGetter, + CallbackInfoReturnable cir) { + BiFunction srcGetter = + sourceGetter != null ? sourceGetter : (id, type) -> null; + + GlShaderModule vertexModule = this.getOrCompileShader(pipeline.getVertexShader(), ShaderType.VERTEX, + pipeline.getShaderDefines(), srcGetter); + GlShaderModule fragmentModule = this.getOrCompileShader(pipeline.getFragmentShader(), ShaderType.FRAGMENT, + pipeline.getShaderDefines(), srcGetter); + + String vertexSource = ((GlShaderModuleExt) vertexModule).vulkanmod$getProcessedSource(); + String fragmentSource = ((GlShaderModuleExt) fragmentModule).vulkanmod$getProcessedSource(); + + if (vertexSource == null || fragmentSource == null) { + throw new IllegalStateException("[VulkanMod] Missing processed GLSL for pipeline %s" + .formatted(pipeline.getLocation())); + } + + GraphicsPipeline graphicsPipeline = VulkanPipelineCompiler.compile(pipeline, vertexSource, fragmentSource); + + int programId = VkGlProgram.genProgramId(); + VkGlProgram vkProgram = VkGlProgram.getProgram(programId); + vkProgram.bindPipeline(graphicsPipeline); + + GlProgram program = GlProgramInvoker.vulkanmod$create(programId, pipeline.getLocation().toString()); + + cir.setReturnValue(new GlRenderPipeline(pipeline, program)); + cir.cancel(); + } + + @Inject(method = "", at = @At("RETURN")) + private void vulkanmod$adjustAlignment(long window, int debugVerbosity, boolean debugSync, + BiFunction shaderSourceGetter, + boolean enableDebugLabels, CallbackInfo ci) { + this.uniformOffsetAlignment = 256; + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/GlProgramInvoker.java b/src/main/java/net/vulkanmod/mixin/render/GlProgramInvoker.java new file mode 100644 index 000000000..ff7c23762 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/GlProgramInvoker.java @@ -0,0 +1,13 @@ +package net.vulkanmod.mixin.render; + +import com.mojang.blaze3d.opengl.GlProgram; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(GlProgram.class) +public interface GlProgramInvoker { + @Invoker("") + static GlProgram vulkanmod$create(int programId, String debugLabel) { + throw new AssertionError(); + } +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/render/GlProgramManagerMixin.java b/src/main/java/net/vulkanmod/mixin/render/GlProgramManagerMixin.java deleted file mode 100644 index b195f1a88..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/GlProgramManagerMixin.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.vulkanmod.mixin.render; - -import com.mojang.blaze3d.shaders.ProgramManager; -import com.mojang.blaze3d.shaders.Shader; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.io.IOException; - -@Mixin(ProgramManager.class) -public class GlProgramManagerMixin { - - @Inject(method = "linkShader", at = @At("HEAD"), cancellable = true) - private static void linkProgram(Shader shader, CallbackInfo ci) throws IOException { - ci.cancel(); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/GlProgramMixin.java b/src/main/java/net/vulkanmod/mixin/render/GlProgramMixin.java new file mode 100644 index 000000000..faa6797d1 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/GlProgramMixin.java @@ -0,0 +1,51 @@ +package net.vulkanmod.mixin.render; + +import com.mojang.blaze3d.opengl.GlProgram; +import com.mojang.blaze3d.opengl.Uniform; +import net.vulkanmod.gl.VkGlProgram; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; + +import java.util.List; +import java.util.Map; + +@Mixin(value = GlProgram.class, remap = false) +public abstract class GlProgramMixin { + + @Shadow(remap = false) + private int programId; + + @Shadow(remap = false) + private Map uniformsByName; + + /** + * Do not query OpenGL for uniforms – VulkanMod manages descriptors separately. + */ + @Overwrite(remap = false) + public void setupUniforms(List uniforms, + List samplers) { + // No-op: uniforms are handled through Vulkan descriptor sets. + } + + /** + * Prevent OpenGL program destruction and forward cleanup to the Vulkan pipeline holder. + */ + @Overwrite(remap = false) + public void close() { + VkGlProgram program = VkGlProgram.getProgram(this.programId); + if (program != null && program.getPipeline() != null) { + program.getPipeline().scheduleCleanUp(); + } + } + + @Overwrite(remap = false) + public Uniform getUniform(String name) { + return this.uniformsByName != null ? this.uniformsByName.get(name) : null; + } + + @Overwrite(remap = false) + public Map getUniforms() { + return this.uniformsByName != null ? this.uniformsByName : Map.of(); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/GlShaderModuleMixin.java b/src/main/java/net/vulkanmod/mixin/render/GlShaderModuleMixin.java new file mode 100644 index 000000000..a313b5deb --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/GlShaderModuleMixin.java @@ -0,0 +1,22 @@ +package net.vulkanmod.mixin.render; + +import com.mojang.blaze3d.opengl.GlShaderModule; +import net.vulkanmod.interfaces.GlShaderModuleExt; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; + +@Mixin(value = GlShaderModule.class, remap = false) +public class GlShaderModuleMixin implements GlShaderModuleExt { + @Unique + private String vulkanmod$processedSource; + + @Override + public void vulkanmod$setProcessedSource(String source) { + this.vulkanmod$processedSource = source; + } + + @Override + public String vulkanmod$getProcessedSource() { + return this.vulkanmod$processedSource; + } +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java index 17b59927e..5b9d21d45 100644 --- a/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java +++ b/src/main/java/net/vulkanmod/mixin/render/GlStateManagerM.java @@ -1,78 +1,36 @@ package net.vulkanmod.mixin.render; -import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.opengl.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; -import net.vulkanmod.gl.*; +import net.vulkanmod.gl.VkGlFramebuffer; +import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import org.jetbrains.annotations.Nullable; -import org.lwjgl.system.MemoryUtil; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.nio.ByteBuffer; -import java.nio.IntBuffer; -@Mixin(GlStateManager.class) +@Mixin(value = GlStateManager.class, remap = false) public class GlStateManagerM { /** * @author + * @reason Route texture binding through the Vulkan-backed texture map. */ @Overwrite(remap = false) - public static void _bindTexture(int i) { - VkGlTexture.bindTexture(i); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _disableBlend() { - RenderSystem.assertOnRenderThread(); - VRenderSystem.disableBlend(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _enableBlend() { - RenderSystem.assertOnRenderThread(); - VRenderSystem.enableBlend(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _blendFunc(int i, int j) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.blendFunc(i, j); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _blendFuncSeparate(int i, int j, int k, int l) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.blendFuncSeparate(i, j, k, l); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _blendEquation(int i) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.blendOp(i); + public static void _bindTexture(int id) { + VkGlTexture.bindTexture(id); } /** * @author + * @reason Forward scissor disables to the Vulkan renderer. */ @Overwrite(remap = false) public static void _disableScissorTest() { @@ -81,36 +39,15 @@ public static void _disableScissorTest() { /** * @author + * @reason Scissor state is tracked on the Vulkan side, no GL enable is required. */ @Overwrite(remap = false) - public static void _enableScissorTest() {} - - /** - * @author - */ - @Overwrite(remap = false) - public static void _enableCull() { - VRenderSystem.enableCull(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _disableCull() { - VRenderSystem.disableCull(); - } - - /** - * @author - */ - @Redirect(method = "_viewport", at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glViewport(IIII)V"), remap = false) - private static void _viewport(int x, int y, int width, int height) { - Renderer.setViewport(x, y, width, height); + public static void _enableScissorTest() { } /** * @author + * @reason Apply scissor bounds via the Vulkan renderer. */ @Overwrite(remap = false) public static void _scissorBox(int x, int y, int width, int height) { @@ -119,401 +56,230 @@ public static void _scissorBox(int x, int y, int width, int height) { /** * @author + * @reason Keep depth testing state in sync with the Vulkan pipeline. */ @Overwrite(remap = false) - public static int _getError() { - return 0; - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, @Nullable IntBuffer pixels) { - RenderSystem.assertOnRenderThread(); - VkGlTexture.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels != null ? MemoryUtil.memByteBuffer(pixels) : null); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _texSubImage2D(int target, int level, int offsetX, int offsetY, int width, int height, int format, int type, long pixels) { - RenderSystem.assertOnRenderThread(); - VkGlTexture.texSubImage2D(target, level, offsetX, offsetY, width, height, format, type, pixels); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _activeTexture(int i) { - VkGlTexture.activeTexture(i); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _texParameter(int i, int j, int k) { - VkGlTexture.texParameteri(i, j, k); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _texParameter(int i, int j, float k) { - //TODO + public static void _disableDepthTest() { + VRenderSystem.disableDepthTest(); } /** * @author + * @reason Keep depth testing state in sync with the Vulkan pipeline. */ @Overwrite(remap = false) - public static int _getTexLevelParameter(int i, int j, int k) { - return VkGlTexture.getTexLevelParameter(i, j, k); + public static void _enableDepthTest() { + VRenderSystem.enableDepthTest(); } /** * @author + * @reason Mirror the configured depth function for the Vulkan backend. */ @Overwrite(remap = false) - public static void _pixelStore(int pname, int param) { - RenderSystem.assertOnRenderThread(); - VkGlTexture.pixelStoreI(pname, param); + public static void _depthFunc(int function) { + VRenderSystem.depthFunc(function); } /** * @author + * @reason Track depth mask changes inside the Vulkan renderer. */ @Overwrite(remap = false) - public static int _genTexture() { - RenderSystem.assertOnRenderThread(); - return VkGlTexture.genTextureId(); + public static void _depthMask(boolean mask) { + VRenderSystem.depthMask(mask); } /** * @author + * @reason Disable blending within the Vulkan state manager. */ @Overwrite(remap = false) - public static void _deleteTexture(int i) { - RenderSystem.assertOnRenderThread(); - VkGlTexture.glDeleteTextures(i); + public static void _disableBlend() { + VRenderSystem.disableBlend(); } /** * @author + * @reason Enable blending within the Vulkan state manager. */ @Overwrite(remap = false) - public static void _colorMask(boolean red, boolean green, boolean blue, boolean alpha) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.colorMask(red, green, blue, alpha); + public static void _enableBlend() { + VRenderSystem.enableBlend(); } /** * @author + * @reason Propagate blend parameters to the Vulkan pipeline. */ @Overwrite(remap = false) - public static void _polygonMode(int face, int mode) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.setPolygonModeGL(mode); + public static void _blendFuncSeparate(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { + VRenderSystem.blendFuncSeparate(srcRgb, dstRgb, srcAlpha, dstAlpha); } /** * @author + * @reason Clear requests are handled by Vulkan rather than GL. */ @Overwrite(remap = false) - public static void _enablePolygonOffset() { - RenderSystem.assertOnRenderThread(); - VRenderSystem.enablePolygonOffset(); + public static void _clear(int mask) { + VRenderSystem.clear(mask); } /** * @author + * @reason Forward viewport updates to Vulkan. */ - @Overwrite(remap = false) - public static void _disablePolygonOffset() { - RenderSystem.assertOnRenderThread(); - VRenderSystem.disablePolygonOffset(); + @Redirect( + method = "_viewport", + at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glViewport(IIII)V"), + remap = false + ) + private static void vulkanmod$setViewport(int x, int y, int width, int height) { + Renderer.setViewport(x, y, width, height); } /** * @author + * @reason No GL error reporting when running on Vulkan. */ @Overwrite(remap = false) - public static void _polygonOffset(float f, float g) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.polygonOffset(g, f); + public static int _getError() { + return 0; } /** * @author + * @reason Upload textures into Vulkan-backed images. */ @Overwrite(remap = false) - public static void _enableColorLogicOp() { + public static void _texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, @Nullable ByteBuffer pixels) { RenderSystem.assertOnRenderThread(); - VRenderSystem.enableColorLogicOp(); + VkGlTexture.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels); } /** * @author + * @reason Upload textures into Vulkan-backed images. */ @Overwrite(remap = false) - public static void _disableColorLogicOp() { + public static void _texSubImage2D(int target, int level, int offsetX, int offsetY, int width, int height, int format, int type, long pixels) { RenderSystem.assertOnRenderThread(); - VRenderSystem.disableColorLogicOp(); + VkGlTexture.texSubImage2D(target, level, offsetX, offsetY, width, height, format, type, pixels); } /** * @author + * @reason Upload textures into Vulkan-backed images. */ @Overwrite(remap = false) - public static void _logicOp(int i) { + public static void _texSubImage2D(int target, int level, int offsetX, int offsetY, int width, int height, int format, int type, ByteBuffer pixels) { RenderSystem.assertOnRenderThread(); - VRenderSystem.logicOp(i); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _clearColor(float f, float g, float h, float i) { - RenderSystem.assertOnRenderThreadOrInit(); - VRenderSystem.setClearColor(f, g, h, i); + VkGlTexture.texSubImage2D(target, level, offsetX, offsetY, width, height, format, type, pixels); } /** * @author + * @reason Track active texture unit inside the Vulkan binding tables. */ @Overwrite(remap = false) - public static void _clearDepth(double d) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.clearDepth(d); + public static void _activeTexture(int texture) { + VkGlTexture.activeTexture(texture); } - /** - * @author - */ - @Overwrite(remap = false) - public static void _clear(int mask, boolean bl) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.clear(mask); + @Inject(method = "_texParameter(III)V", at = @At("HEAD"), cancellable = true, remap = false) + private static void vulkanmod$texParameterInt(int target, int pname, int param, CallbackInfo ci) { + VkGlTexture.texParameteri(target, pname, param); + ci.cancel(); } /** * @author + * @reason Maintain pixel store state for Vulkan texture uploads. */ @Overwrite(remap = false) - public static void _disableDepthTest() { - RenderSystem.assertOnRenderThread(); - VRenderSystem.disableDepthTest(); + public static void _pixelStore(int pname, int param) { + VkGlTexture.pixelStoreI(pname, param); } /** * @author + * @reason Allocate Vulkan texture handles instead of GL textures. */ @Overwrite(remap = false) - public static void _enableDepthTest() { - RenderSystem.assertOnRenderThread(); - VRenderSystem.enableDepthTest(); + public static int _genTexture() { + return VkGlTexture.genTextureId(); } /** * @author + * @reason Release Vulkan texture handles when GL deletes textures. */ @Overwrite(remap = false) - public static void _depthFunc(int i) { - RenderSystem.assertOnRenderThreadOrInit(); - VRenderSystem.depthFunc(i); + public static void _deleteTexture(int id) { + VkGlTexture.glDeleteTextures(id); } /** * @author + * @reason Bind framebuffers through the Vulkan compatibility layer. */ @Overwrite(remap = false) - public static void _depthMask(boolean bl) { - RenderSystem.assertOnRenderThread(); - VRenderSystem.depthMask(bl); - + public static void _glBindFramebuffer(int target, int framebuffer) { + VkGlFramebuffer.bindFramebuffer(target, framebuffer); } /** * @author + * @reason Create framebuffer identifiers provided by the Vulkan layer. */ @Overwrite(remap = false) public static int glGenFramebuffers() { - RenderSystem.assertOnRenderThread(); return VkGlFramebuffer.genFramebufferId(); } /** * @author + * @reason Attach textures managed by Vulkan to framebuffer slots. */ @Overwrite(remap = false) - public static int glGenRenderbuffers() { - RenderSystem.assertOnRenderThreadOrInit(); - return VkGlRenderbuffer.genId(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _glBindFramebuffer(int i, int j) { - RenderSystem.assertOnRenderThread(); - VkGlFramebuffer.bindFramebuffer(i, j); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _glFramebufferTexture2D(int i, int j, int k, int l, int m) { - RenderSystem.assertOnRenderThread(); - VkGlFramebuffer.framebufferTexture2D(i, j, k, l, m); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _glBindRenderbuffer(int i, int j) { - RenderSystem.assertOnRenderThreadOrInit(); - VkGlRenderbuffer.bindRenderbuffer(i, j); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _glFramebufferRenderbuffer(int i, int j, int k, int l) { - RenderSystem.assertOnRenderThreadOrInit(); - VkGlFramebuffer.framebufferRenderbuffer(i, j, k, l); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _glRenderbufferStorage(int i, int j, int k, int l) { - RenderSystem.assertOnRenderThreadOrInit(); - VkGlRenderbuffer.renderbufferStorage(i, j, k, l); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static int glCheckFramebufferStatus(int i) { - RenderSystem.assertOnRenderThreadOrInit(); - return VkGlFramebuffer.glCheckFramebufferStatus(i); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static int _glGenBuffers() { - RenderSystem.assertOnRenderThreadOrInit(); - return VkGlBuffer.glGenBuffers(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _glBindBuffer(int i, int j) { - RenderSystem.assertOnRenderThread(); - VkGlBuffer.glBindBuffer(i, j); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _glBufferData(int i, ByteBuffer byteBuffer, int j) { - RenderSystem.assertOnRenderThread(); - VkGlBuffer.glBufferData(i, byteBuffer, j); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void _glBufferData(int i, long l, int j) { - RenderSystem.assertOnRenderThread(); - VkGlBuffer.glBufferData(i, l, j); - } - - /** - * @author - */ - @Overwrite(remap = false) - @Nullable - public static ByteBuffer _glMapBuffer(int i, int j) { - RenderSystem.assertOnRenderThreadOrInit(); - return VkGlBuffer.glMapBuffer(i, j); + public static void _glFramebufferTexture2D(int target, int attachment, int textarget, int texture, int level) { + VkGlFramebuffer.framebufferTexture2D(target, attachment, textarget, texture, level); } /** * @author + * @reason Present operations are handled explicitly; default GL blit is unused. */ @Overwrite(remap = false) - public static void _glUnmapBuffer(int i) { - RenderSystem.assertOnRenderThread(); - VkGlBuffer.glUnmapBuffer(i); + public static void _glBlitFrameBuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter) { + VkGlFramebuffer.glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); } /** * @author + * @reason Ensure Vulkan framebuffers are cleaned alongside GL calls. */ @Overwrite(remap = false) - public static void _glDeleteBuffers(int i) { - RenderSystem.assertOnRenderThread(); - VkGlBuffer.glDeleteBuffers(i); + public static void _glDeleteFramebuffers(int framebuffer) { + VkGlFramebuffer.deleteFramebuffer(framebuffer); } /** * @author + * @reason Cull state is tracked on the Vulkan renderer. */ @Overwrite(remap = false) - public static void _disableVertexAttribArray(int i) {} - - /** - * @author - */ - @Overwrite(remap = false) - public static void _glUseProgram(int i) { - RenderSystem.assertOnRenderThread(); - VkGlProgram.glUseProgram(i); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static int glCreateProgram() { - RenderSystem.assertOnRenderThread(); - return VkGlProgram.genProgramId(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void glDeleteProgram(int i) { - RenderSystem.assertOnRenderThread(); -// GL20.glDeleteProgram(i); + public static void _enableCull() { + VRenderSystem.enableCull(); } /** * @author + * @reason Cull state is tracked on the Vulkan renderer. */ @Overwrite(remap = false) - public static int _glGenVertexArrays() { - RenderSystem.assertOnRenderThreadOrInit(); - // TODO - return 0; + public static void _disableCull() { + VRenderSystem.disableCull(); } } diff --git a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java index 2b42bbcdd..e8b7a3b24 100644 --- a/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/MinecraftMixin.java @@ -1,6 +1,5 @@ package net.vulkanmod.mixin.render; -import com.mojang.blaze3d.systems.TimerQuery; import net.minecraft.client.GraphicsStatus; import net.minecraft.client.Minecraft; import net.minecraft.client.Options; @@ -13,18 +12,21 @@ import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; - -import java.util.Optional; @Mixin(Minecraft.class) public class MinecraftMixin { - @Shadow @Final public Options options; + @Shadow + @Final + public Options options; + @Unique + private int vulkanmod$ticksRemaining; @Inject(method = "", at = @At(value = "RETURN")) private void forceGraphicsMode(GameConfig gameConfig, CallbackInfo ci) { @@ -36,17 +38,29 @@ private void forceGraphicsMode(GameConfig gameConfig, CallbackInfo ci) { } } - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/TimerQuery;getInstance()Ljava/util/Optional;")) - private Optional removeTimer() { - return Optional.empty(); + @Inject(method = "runTick", at = @At("HEAD")) + private void vulkanmod$resetTickBudget(boolean bl, CallbackInfo ci) { + this.vulkanmod$ticksRemaining = 0; + SpriteUpdateUtil.setDoUpload(true); + } + + @ModifyVariable(method = "runTick", at = @At(value = "STORE"), ordinal = 0) + private int vulkanmod$captureTickBudget(int tickBudget) { + this.vulkanmod$ticksRemaining = Math.min(10, tickBudget); + if (this.vulkanmod$ticksRemaining == 0) { + SpriteUpdateUtil.setDoUpload(true); + } + return tickBudget; } - @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;tick()V"), - locals = LocalCapture.CAPTURE_FAILHARD) - private void redirectResourceTick(boolean bl, CallbackInfo ci, Runnable runnable, int i, int j) { - int n = Math.min(10, i) - 1; - boolean doUpload = j == n; - SpriteUpdateUtil.setDoUpload(doUpload); + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;tick()V")) + private void vulkanmod$wrapTickForUploads(Minecraft instance) { + int remaining = this.vulkanmod$ticksRemaining; + SpriteUpdateUtil.setDoUpload(remaining <= 1); + if (remaining > 0) { + this.vulkanmod$ticksRemaining = remaining - 1; + } + instance.tick(); } @Inject(method = "close", at = @At(value = "HEAD")) @@ -66,6 +80,7 @@ public void onResolutionChanged(CallbackInfo ci) { // Fixes crash when minimizing window before setScreen is called @Redirect(method = "setScreen", at = @At(value = "FIELD", target = "Lnet/minecraft/client/Minecraft;noRender:Z", opcode = Opcodes.PUTFIELD)) - private void keepVar(Minecraft instance, boolean value) {} + private void keepVar(Minecraft instance, boolean value) { + } } diff --git a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java index 1a173834a..9108b5f28 100644 --- a/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/RenderSystemMixin.java @@ -1,193 +1,137 @@ package net.vulkanmod.mixin.render; +import com.mojang.blaze3d.ProjectionType; +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.buffers.GpuBufferSlice; import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.VertexSorting; +import net.minecraft.resources.ResourceLocation; import net.vulkanmod.vulkan.VRenderSystem; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; import org.joml.Matrix4fStack; -import org.joml.Vector3f; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; +import org.lwjgl.system.MemoryUtil; +import org.spongepowered.asm.mixin.*; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import static com.mojang.blaze3d.systems.RenderSystem.*; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; +import java.util.function.BiFunction; -@Mixin(RenderSystem.class) +@Mixin(value = RenderSystem.class, remap = false) public abstract class RenderSystemMixin { - @Shadow private static Matrix4f projectionMatrix; - @Shadow private static Matrix4f savedProjectionMatrix; - @Shadow @Final private static Matrix4fStack modelViewStack; - @Shadow private static Matrix4f modelViewMatrix; - @Shadow private static Matrix4f textureMatrix; - - @Shadow @Final private static float[] shaderColor; - @Shadow @Final private static Vector3f[] shaderLightDirections; - @Shadow @Final private static float[] shaderFogColor; - - @Shadow private static @Nullable Thread renderThread; - - @Shadow public static VertexSorting vertexSorting; - @Shadow private static VertexSorting savedVertexSorting; + @Shadow + @Final + private static Matrix4fStack modelViewStack; + @Shadow + private static Matrix4f textureMatrix; + @Shadow + private static @Nullable Thread renderThread; + @Shadow + @Nullable + private static GpuBufferSlice shaderFog; + @Shadow + @Nullable + private static GpuBufferSlice shaderLightDirections; + @Shadow + @Nullable + private static GpuBufferSlice projectionMatrixBuffer; + @Shadow + private static ProjectionType projectionType; + @Shadow + private static ProjectionType savedProjectionType; + @Shadow + @Nullable + private static GpuBufferSlice savedProjectionMatrixBuffer; @Shadow - public static void assertOnRenderThread() {} + public static void assertOnRenderThread() { + } - /** - * @author - */ - @Overwrite(remap = false) - public static void initRenderer(int debugVerbosity, boolean debugSync) { + @Inject(method = "initRenderer(JIZLjava/util/function/BiFunction;Z)V", at = @At("TAIL")) + private static void hookInitRenderer(long window, int debugVerbosity, boolean debugSync, + BiFunction shaderSourceGetter, + boolean enableDebugLabels, CallbackInfo ci) { + VRenderSystem.setWindow(window); VRenderSystem.initRenderer(); - renderThread.setPriority(Thread.NORM_PRIORITY + 2); + if (renderThread != null) { + renderThread.setPriority(Thread.NORM_PRIORITY + 2); + } } - /** - * @author - */ @Overwrite(remap = false) - public static void setupDefaultState(int x, int y, int width, int height) { } - - /** - * @author - */ - @Overwrite(remap = false) - public static int maxSupportedTextureSize() { - return VRenderSystem.maxSupportedTextureSize(); + public static void setupDefaultState() { } - /** - * @author - */ - @Overwrite(remap = false) - public static void setShaderLights(Vector3f dir0, Vector3f dir1) { - shaderLightDirections[0] = dir0; - shaderLightDirections[1] = dir1; - - VRenderSystem.lightDirection0.buffer.putFloat(0, dir0.x()); - VRenderSystem.lightDirection0.buffer.putFloat(4, dir0.y()); - VRenderSystem.lightDirection0.buffer.putFloat(8, dir0.z()); - - VRenderSystem.lightDirection1.buffer.putFloat(0, dir1.x()); - VRenderSystem.lightDirection1.buffer.putFloat(4, dir1.y()); - VRenderSystem.lightDirection1.buffer.putFloat(8, dir1.z()); + @Inject(method = "setProjectionMatrix", at = @At("TAIL")) + private static void captureProjection(GpuBufferSlice buffer, ProjectionType type, CallbackInfo ci) { + updateProjection(buffer); } - /** - * @author - */ - @Overwrite(remap = false) - private static void _setShaderColor(float r, float g, float b, float a) { - shaderColor[0] = r; - shaderColor[1] = g; - shaderColor[2] = b; - shaderColor[3] = a; - - VRenderSystem.setShaderColor(r, g, b, a); + @Inject(method = "restoreProjectionMatrix", at = @At("TAIL")) + private static void captureRestoredProjection(CallbackInfo ci) { + if (projectionMatrixBuffer != null) { + updateProjection(projectionMatrixBuffer); + } } - /** - * @author - */ - @Overwrite(remap = false) - public static void setShaderFogColor(float f, float g, float h, float i) { - shaderFogColor[0] = f; - shaderFogColor[1] = g; - shaderFogColor[2] = h; - shaderFogColor[3] = i; - - VRenderSystem.setShaderFogColor(f, g, h, i); + @Inject(method = "setShaderFog", at = @At("TAIL")) + private static void captureFog(GpuBufferSlice buffer, CallbackInfo ci) { + shaderFog = buffer; } - /** - * @author - */ - @Overwrite(remap = false) - public static void setProjectionMatrix(Matrix4f projectionMatrix, VertexSorting vertexSorting) { - Matrix4f matrix4f = new Matrix4f(projectionMatrix); - if (!isOnRenderThread()) { - recordRenderCall(() -> { - RenderSystemMixin.projectionMatrix = matrix4f; - RenderSystem.vertexSorting = vertexSorting; - - VRenderSystem.applyProjectionMatrix(matrix4f); - VRenderSystem.calculateMVP(); - }); - } else { - RenderSystemMixin.projectionMatrix = matrix4f; - RenderSystem.vertexSorting = vertexSorting; - - VRenderSystem.applyProjectionMatrix(matrix4f); - VRenderSystem.calculateMVP(); + @Inject(method = "setShaderLights", at = @At("TAIL")) + private static void captureLights(GpuBufferSlice buffer, CallbackInfo ci) { + shaderLightDirections = buffer; + if (buffer != null) { + updateLights(buffer); } - } - /** - * @author - */ - @Overwrite(remap = false) - public static void setTextureMatrix(Matrix4f matrix4f) { - Matrix4f matrix4f2 = new Matrix4f(matrix4f); - if (!RenderSystem.isOnRenderThread()) { - RenderSystem.recordRenderCall(() -> { - textureMatrix = matrix4f2; - VRenderSystem.setTextureMatrix(matrix4f); - }); - } else { - textureMatrix = matrix4f2; - VRenderSystem.setTextureMatrix(matrix4f); - } + @Inject(method = "setTextureMatrix", at = @At("TAIL")) + private static void propagateTextureMatrix(Matrix4f matrix, CallbackInfo ci) { + VRenderSystem.setTextureMatrix(matrix); } - /** - * @author - */ - @Overwrite(remap = false) - public static void resetTextureMatrix() { - if (!RenderSystem.isOnRenderThread()) { - RenderSystem.recordRenderCall(() -> textureMatrix.identity()); - } else { - textureMatrix.identity(); - VRenderSystem.setTextureMatrix(textureMatrix); - } + @Inject(method = "resetTextureMatrix", at = @At("TAIL")) + private static void propagateTextureReset(CallbackInfo ci) { + VRenderSystem.setTextureMatrix(textureMatrix); } - /** - * @author - */ - @Overwrite(remap = false) - public static void applyModelViewMatrix() { - Matrix4f matrix4f = new Matrix4f(modelViewStack); - if (!isOnRenderThread()) { - recordRenderCall(() -> { - modelViewMatrix = matrix4f; - //Vulkan - VRenderSystem.applyModelViewMatrix(matrix4f); + @Unique + private static void updateProjection(GpuBufferSlice slice) { + try (GpuBuffer.MappedView view = RenderSystem.getDevice().createCommandEncoder().mapBuffer(slice, true, false)) { + FloatBuffer buffer = view.data().order(ByteOrder.nativeOrder()).asFloatBuffer(); + FloatBuffer copy = MemoryUtil.memAllocFloat(16); + try { + for (int i = 0; i < 16; i++) { + copy.put(i, buffer.get(i)); + } + copy.position(0); + Matrix4f matrix = new Matrix4f(); + matrix.set(copy); + VRenderSystem.applyProjectionMatrix(matrix); VRenderSystem.calculateMVP(); - }); - } else { - modelViewMatrix = matrix4f; - - VRenderSystem.applyModelViewMatrix(matrix4f); - VRenderSystem.calculateMVP(); + } finally { + MemoryUtil.memFree(copy); + } } - } - /** - * @author - */ - @Overwrite(remap = false) - private static void _restoreProjectionMatrix() { - projectionMatrix = savedProjectionMatrix; - vertexSorting = savedVertexSorting; - - VRenderSystem.applyProjectionMatrix(projectionMatrix); - VRenderSystem.calculateMVP(); + @Unique + private static void updateLights(GpuBufferSlice slice) { + try (GpuBuffer.MappedView view = RenderSystem.getDevice().createCommandEncoder().mapBuffer(slice, true, false)) { + FloatBuffer buffer = view.data().order(ByteOrder.nativeOrder()).asFloatBuffer(); + float lx0 = buffer.get(0); + float ly0 = buffer.get(1); + float lz0 = buffer.get(2); + float lx1 = buffer.get(4); + float ly1 = buffer.get(5); + float lz1 = buffer.get(6); + VRenderSystem.setShaderLights(lx0, ly0, lz0, lx1, ly1, lz1); + } } - } diff --git a/src/main/java/net/vulkanmod/mixin/render/RenderTypeM.java b/src/main/java/net/vulkanmod/mixin/render/RenderTypeM.java index adae96e46..256a5f076 100644 --- a/src/main/java/net/vulkanmod/mixin/render/RenderTypeM.java +++ b/src/main/java/net/vulkanmod/mixin/render/RenderTypeM.java @@ -1,6 +1,5 @@ package net.vulkanmod.mixin.render; -import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.RenderType; import net.vulkanmod.interfaces.ExtendedRenderType; import net.vulkanmod.render.vertex.TerrainRenderType; @@ -12,9 +11,9 @@ @Mixin(RenderType.class) public class RenderTypeM implements ExtendedRenderType { TerrainRenderType terrainRenderType; - + @Inject(method = "", at = @At("RETURN")) - private void inj(String string, VertexFormat vertexFormat, VertexFormat.Mode mode, int i, boolean bl, boolean bl2, Runnable runnable, Runnable runnable2, CallbackInfo ci) { + private void inj(String string, int i, boolean bl, boolean bl2, Runnable runnable, Runnable runnable2, CallbackInfo ci) { terrainRenderType = switch (string) { case "solid" -> TerrainRenderType.SOLID; case "cutout" -> TerrainRenderType.CUTOUT; @@ -24,9 +23,9 @@ private void inj(String string, VertexFormat vertexFormat, VertexFormat.Mode mod default -> null; }; } - + @Override public TerrainRenderType getTerrainRenderType() { return terrainRenderType; } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java b/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java deleted file mode 100644 index b63cd779f..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/ShaderInstanceM.java +++ /dev/null @@ -1,356 +0,0 @@ -package net.vulkanmod.mixin.render; - -import com.google.gson.JsonObject; -import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.platform.Window; -import com.mojang.blaze3d.shaders.Program; -import com.mojang.blaze3d.shaders.ProgramManager; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.ShaderInstance; -import net.minecraft.client.renderer.texture.AbstractTexture; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceProvider; -import net.vulkanmod.Initializer; -import net.vulkanmod.gl.VkGlProgram; -import net.vulkanmod.interfaces.ShaderMixed; -import net.vulkanmod.render.shader.ShaderLoadUtil; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.shader.descriptor.UBO; -import net.vulkanmod.vulkan.shader.layout.Uniform; -import net.vulkanmod.vulkan.shader.converter.GlslConverter; -import net.vulkanmod.vulkan.texture.VTextureSelector; -import net.vulkanmod.vulkan.util.MappedBuffer; -import org.apache.commons.io.IOUtils; -import org.jetbrains.annotations.Nullable; -import org.joml.Matrix4f; -import org.lwjgl.system.MemoryUtil; -import org.spongepowered.asm.mixin.*; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; - -@Mixin(ShaderInstance.class) -public class ShaderInstanceM implements ShaderMixed { - - @Shadow @Final private Map uniformMap; - @Shadow @Final private String name; - - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform MODEL_VIEW_MATRIX; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform PROJECTION_MATRIX; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform COLOR_MODULATOR; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform LINE_WIDTH; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform GLINT_ALPHA; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform FOG_START; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform FOG_END; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform FOG_COLOR; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform FOG_SHAPE; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform TEXTURE_MATRIX; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform GAME_TIME; - @Shadow @Final @Nullable public com.mojang.blaze3d.shaders.Uniform SCREEN_SIZE; - - @Shadow @Final private Map samplerMap; - @Shadow @Final private List samplerLocations; - @Shadow @Final private List samplerNames; - - @Shadow @Final private List uniforms; - @Shadow @Final private VertexFormat vertexFormat; - @Shadow @Final private int programId; - @Shadow private static int lastProgramId; - @Unique private String vsPath; - @Unique private String fsName; - - @Unique private GraphicsPipeline pipeline; - @Unique boolean doUniformUpdate = false; - - public GraphicsPipeline getPipeline() { - return pipeline; - } - - @Inject(method = "", at = @At("RETURN")) - private void create(ResourceProvider resourceProvider, String name, VertexFormat format, CallbackInfo ci) { - String configName = name; - JsonObject config = ShaderLoadUtil.getJsonConfig("core", configName); - - if (config == null) { - createLegacyShader(resourceProvider, format); - } else { - createPipeline(configName, format, config); - } - - VkGlProgram program = VkGlProgram.getProgram(this.programId); - program.bindPipeline(this.pipeline); - } - - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ShaderInstance;getOrCreate(Lnet/minecraft/server/packs/resources/ResourceProvider;Lcom/mojang/blaze3d/shaders/Program$Type;Ljava/lang/String;)Lcom/mojang/blaze3d/shaders/Program;")) - private Program loadNames(ResourceProvider resourceProvider, Program.Type type, String name) { - String path; - if (this.name.contains(String.valueOf(ResourceLocation.NAMESPACE_SEPARATOR))) { - ResourceLocation location = ResourceLocation.tryParse(name); - path = location.withPath("shaders/core/%s".formatted(location.getPath())).toString(); - } else { - path = "shaders/core/%s".formatted(name); - } - - switch (type) { - case VERTEX -> this.vsPath = path; - case FRAGMENT -> this.fsName = path; - } - - return null; - } - - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/shaders/Uniform;glBindAttribLocation(IILjava/lang/CharSequence;)V")) - private void bindAttr(int program, int index, CharSequence name) {} - - /** - * @author - */ - @Overwrite - public void close() { - if (this.pipeline != null) - this.pipeline.cleanUp(); - } - - /** - * @author - */ - @Overwrite - public void apply() { - if (this.doUniformUpdate) { - - for(int j = 0; j < this.samplerLocations.size(); ++j) { - String string = this.samplerNames.get(j); - if (this.samplerMap.get(string) != null) { - RenderSystem.activeTexture(33984 + j); - Object object = this.samplerMap.get(string); - int texId = -1; - if (object instanceof RenderTarget) { - texId = ((RenderTarget)object).getColorTextureId(); - } else if (object instanceof AbstractTexture) { - texId = ((AbstractTexture)object).getId(); - } else if (object instanceof Integer) { - texId = (Integer)object; - } - - if (texId != -1) { - RenderSystem.bindTexture(texId); - RenderSystem.setShaderTexture(j, texId); - } - } - } - - for (com.mojang.blaze3d.shaders.Uniform uniform : this.uniforms) { - uniform.upload(); - } - - } - - if (this.programId != lastProgramId) { - ProgramManager.glUseProgram(this.programId); - lastProgramId = this.programId; - } - - bindPipeline(); - } - - /** - * @author - */ - @Overwrite - public void setDefaultUniforms(VertexFormat.Mode mode, Matrix4f modelView, Matrix4f projection, Window window) { - if (!this.doUniformUpdate) - return; - - if (this.MODEL_VIEW_MATRIX != null) { - this.MODEL_VIEW_MATRIX.set(modelView); - } - - if (this.PROJECTION_MATRIX != null) { - this.PROJECTION_MATRIX.set(projection); - } - - if (this.COLOR_MODULATOR != null) { - this.COLOR_MODULATOR.set(RenderSystem.getShaderColor()); - } - - if (this.GLINT_ALPHA != null) { - this.GLINT_ALPHA.set(RenderSystem.getShaderGlintAlpha()); - } - - if (this.FOG_START != null) { - this.FOG_START.set(RenderSystem.getShaderFogStart()); - } - - if (this.FOG_END != null) { - this.FOG_END.set(RenderSystem.getShaderFogEnd()); - } - - if (this.FOG_COLOR != null) { - this.FOG_COLOR.set(RenderSystem.getShaderFogColor()); - } - - if (this.FOG_SHAPE != null) { - this.FOG_SHAPE.set(RenderSystem.getShaderFogShape().getIndex()); - } - - if (this.TEXTURE_MATRIX != null) { - this.TEXTURE_MATRIX.set(RenderSystem.getTextureMatrix()); - } - - if (this.GAME_TIME != null) { - this.GAME_TIME.set(RenderSystem.getShaderGameTime()); - } - - if (this.SCREEN_SIZE != null) { - this.SCREEN_SIZE.set((float)window.getWidth(), (float)window.getHeight()); - } - - if (this.LINE_WIDTH != null && (mode == VertexFormat.Mode.LINES || mode == VertexFormat.Mode.LINE_STRIP)) { - this.LINE_WIDTH.set(RenderSystem.getShaderLineWidth()); - } - - RenderSystem.setupShaderLights((ShaderInstance) (Object) this); - } - - /** - * @author - */ - @Overwrite - public void clear() {} - - @Unique - private void bindPipeline() { - if (this.pipeline == null) { - throw new NullPointerException("Shader %s has no initialized pipeline".formatted(this.name)); - } - - Renderer renderer = Renderer.getInstance(); - renderer.bindGraphicsPipeline(pipeline); - VTextureSelector.bindShaderTextures(pipeline); - renderer.uploadAndBindUBOs(pipeline); - } - - public void setupUniformSuppliers(UBO ubo) { - for (Uniform vUniform : ubo.getUniforms()) { - com.mojang.blaze3d.shaders.Uniform uniform = this.uniformMap.get(vUniform.getName()); - - Supplier supplier; - ByteBuffer byteBuffer; - - if (uniform == null) { - Initializer.LOGGER.error(String.format("Error: field %s not present in uniform map", vUniform.getName())); - - int size = vUniform.getSize(); - byteBuffer = MemoryUtil.memAlloc(size * 4); - } - else if (uniform.getType() <= 3) { - byteBuffer = MemoryUtil.memByteBuffer(uniform.getIntBuffer()); - } else if (uniform.getType() <= 10) { - byteBuffer = MemoryUtil.memByteBuffer(uniform.getFloatBuffer()); - } else { - throw new RuntimeException("out of bounds value for uniform " + uniform); - } - - - MappedBuffer mappedBuffer = MappedBuffer.createFromBuffer(byteBuffer); - supplier = () -> mappedBuffer; - - vUniform.setSupplier(supplier); - } - - } - - public Supplier getUniformSupplier(String name) { - com.mojang.blaze3d.shaders.Uniform uniform1 = this.uniformMap.get(name); - - if (uniform1 == null) { - Initializer.LOGGER.error(String.format("Error: field %s not present in uniform map", name)); - return null; - } - - Supplier supplier; - ByteBuffer byteBuffer; - - if (uniform1.getType() <= 3) { - byteBuffer = MemoryUtil.memByteBuffer(uniform1.getIntBuffer()); - } else if (uniform1.getType() <= 10) { - byteBuffer = MemoryUtil.memByteBuffer(uniform1.getFloatBuffer()); - } else { - throw new RuntimeException("out of bounds value for uniform " + uniform1); - } - - MappedBuffer mappedBuffer = MappedBuffer.createFromBuffer(byteBuffer); - supplier = () -> mappedBuffer; - - return supplier; - } - - @Override - public void setDoUniformsUpdate() { - this.doUniformUpdate = true; - } - - @Override - public void setPipeline(GraphicsPipeline graphicsPipeline) { - this.pipeline = graphicsPipeline; - } - - @Unique - private void createPipeline(String configName, VertexFormat format, JsonObject config) { - Pipeline.Builder builder = new Pipeline.Builder(format, configName); - builder.setUniformSupplierGetter(info -> this.getUniformSupplier(info.name)); - - builder.parseBindings(config); - - ShaderLoadUtil.loadShaders(builder, config, configName, "core"); - - GraphicsPipeline pipeline = builder.createGraphicsPipeline(); - this.pipeline = pipeline; - } - - @Unique - private void createLegacyShader(ResourceProvider resourceProvider, VertexFormat format) { - try { - String vertPath = this.vsPath + ".vsh"; - Resource resource = resourceProvider.getResourceOrThrow(ResourceLocation.tryParse(vertPath)); - InputStream inputStream = resource.open(); - String vshSrc = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - - String fragPath = this.fsName + ".fsh"; - resource = resourceProvider.getResourceOrThrow(ResourceLocation.tryParse(fragPath)); - inputStream = resource.open(); - String fshSrc = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - - GlslConverter converter = new GlslConverter(); - Pipeline.Builder builder = new Pipeline.Builder(format, this.name); - - converter.process(vshSrc, fshSrc); - UBO ubo = converter.createUBO(); - this.setupUniformSuppliers(ubo); - this.setDoUniformsUpdate(); - - builder.setUniforms(Collections.singletonList(ubo), converter.getSamplerList()); - builder.compileShaders(this.name, converter.getVshConverted(), converter.getFshConverted()); - - this.pipeline = builder.createGraphicsPipeline(); - this.doUniformUpdate = true; - } catch (Exception e) { - Initializer.LOGGER.error("Error on shader {} conversion/compilation", this.name); - e.printStackTrace(); - } - } -} - diff --git a/src/main/java/net/vulkanmod/mixin/render/accessor/ShaderCompilationKeyAccessor.java b/src/main/java/net/vulkanmod/mixin/render/accessor/ShaderCompilationKeyAccessor.java new file mode 100644 index 000000000..cbdfe0217 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/accessor/ShaderCompilationKeyAccessor.java @@ -0,0 +1,19 @@ +package net.vulkanmod.mixin.render.accessor; + +import com.mojang.blaze3d.shaders.ShaderType; +import net.minecraft.client.renderer.ShaderDefines; +import net.minecraft.resources.ResourceLocation; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +@Mixin(targets = "com.mojang.blaze3d.opengl.GlDevice$ShaderCompilationKey", remap = false) +public interface ShaderCompilationKeyAccessor { + @Accessor("id") + ResourceLocation vulkanmod$getId(); + + @Accessor("type") + ShaderType vulkanmod$getType(); + + @Accessor("defines") + ShaderDefines vulkanmod$getDefines(); +} diff --git a/src/main/java/net/vulkanmod/mixin/render/biome/BiomeManagerM.java b/src/main/java/net/vulkanmod/mixin/render/biome/BiomeManagerM.java index 7ec047b32..4b9d386a0 100644 --- a/src/main/java/net/vulkanmod/mixin/render/biome/BiomeManagerM.java +++ b/src/main/java/net/vulkanmod/mixin/render/biome/BiomeManagerM.java @@ -9,7 +9,9 @@ @Mixin(BiomeManager.class) public class BiomeManagerM implements BiomeManagerExtended { - @Shadow @Final private long biomeZoomSeed; + @Shadow + @Final + private long biomeZoomSeed; @Override public long getBiomeZoomSeed() { diff --git a/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java b/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java index 1f012d472..ddc63eb48 100644 --- a/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java +++ b/src/main/java/net/vulkanmod/mixin/render/block/BakedQuadM.java @@ -3,10 +3,10 @@ import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; -import net.vulkanmod.render.chunk.build.frapi.helper.NormalHelper; +import net.vulkanmod.render.chunk.build.pipeline.helper.NormalHelper; import net.vulkanmod.render.chunk.cull.QuadFacing; -import net.vulkanmod.render.model.quad.ModelQuadView; import net.vulkanmod.render.model.quad.ModelQuadFlags; +import net.vulkanmod.render.model.quad.ModelQuadView; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -19,14 +19,24 @@ @Mixin(BakedQuad.class) public class BakedQuadM implements ModelQuadView { - @Shadow @Final protected int[] vertices; - @Shadow @Final protected Direction direction; - @Shadow @Final protected int tintIndex; + @Shadow + @Final + protected int[] vertices; + @Shadow + @Final + protected Direction direction; + @Shadow + @Final + protected int tintIndex; private int flags; private int normal; private QuadFacing facing; + private static int vertexOffset(int vertexIndex) { + return vertexIndex * VERTEX_SIZE; + } + @Inject(method = "", at = @At("RETURN")) private void onInit(int[] vertices, int tintIndex, Direction face, TextureAtlasSprite textureAtlasSprite, boolean shade, CallbackInfo ci) { this.flags = ModelQuadFlags.getQuadFlags(this, face); @@ -100,8 +110,4 @@ public int getNormal() { public boolean isTinted() { return this.tintIndex != -1; } - - private static int vertexOffset(int vertexIndex) { - return vertexIndex * VERTEX_SIZE; - } } diff --git a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java index a5680870a..4902ee0a4 100644 --- a/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java +++ b/src/main/java/net/vulkanmod/mixin/render/clouds/LevelRendererM.java @@ -1,14 +1,16 @@ package net.vulkanmod.mixin.render.clouds; -import com.mojang.blaze3d.vertex.*; +import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.*; +import net.minecraft.client.renderer.LevelRenderer; import net.minecraft.server.packs.resources.ResourceManager; import net.vulkanmod.render.profiling.Profiler; import net.vulkanmod.render.sky.CloudRenderer; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; -import org.spongepowered.asm.mixin.*; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -16,8 +18,10 @@ @Mixin(LevelRenderer.class) public abstract class LevelRendererM { - @Shadow private int ticks; - @Shadow private @Nullable ClientLevel level; + @Shadow + private int ticks; + @Shadow + private @Nullable ClientLevel level; @Unique private CloudRenderer cloudRenderer; @@ -47,4 +51,4 @@ private void onReload(ResourceManager resourceManager, CallbackInfo ci) { } } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/render/color/BlockColorsM.java b/src/main/java/net/vulkanmod/mixin/render/color/BlockColorsM.java index b3480e5c9..ce67b22cb 100644 --- a/src/main/java/net/vulkanmod/mixin/render/color/BlockColorsM.java +++ b/src/main/java/net/vulkanmod/mixin/render/color/BlockColorsM.java @@ -14,16 +14,16 @@ @Mixin(BlockColors.class) public class BlockColorsM implements BlockColorsExtended { - @Unique - private BlockColorRegistry colorResolvers = new BlockColorRegistry(); + @Unique + private BlockColorRegistry colorResolvers = new BlockColorRegistry(); - @Inject(method = "register", at = @At("RETURN")) - private void onRegister(BlockColor blockColor, Block[] blocks, CallbackInfo ci) { - this.colorResolvers.register(blockColor, blocks); - } + @Inject(method = "register", at = @At("RETURN")) + private void onRegister(BlockColor blockColor, Block[] blocks, CallbackInfo ci) { + this.colorResolvers.register(blockColor, blocks); + } - @Override - public BlockColorRegistry getColorResolverMap() { - return this.colorResolvers; - } + @Override + public BlockColorRegistry getColorResolverMap() { + return this.colorResolvers; + } } diff --git a/src/main/java/net/vulkanmod/mixin/render/entity/EntityRendererM.java b/src/main/java/net/vulkanmod/mixin/render/entity/EntityRendererM.java index c8503bc8d..590b7ba1a 100644 --- a/src/main/java/net/vulkanmod/mixin/render/entity/EntityRendererM.java +++ b/src/main/java/net/vulkanmod/mixin/render/entity/EntityRendererM.java @@ -33,22 +33,22 @@ public class EntityRendererM { // //// WorldRenderer.getInstance().getSectionGrid().getSectionAtBlockPos((int) entity.getX(), (int) entity.getY(), (int) entity.getZ()); // WorldRenderer worldRenderer = WorldRenderer.getInstance(); -//// return (worldRenderer.getLastFrame() == worldRenderer.getSectionGrid().getSectionAtBlockPos(entity.getBlockX(), entity.getBlockY(), entity.getBlockZ()).getLastFrame()); + + /// / return (worldRenderer.getLastFrame() == worldRenderer.getSectionGrid().getSectionAtBlockPos(entity.getBlockX(), entity.getBlockY(), entity.getBlockZ()).getLastFrame()); // // return frustum.isVisible(aABB); // } // } - @Redirect(method = "shouldRender", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/culling/Frustum;isVisible(Lnet/minecraft/world/phys/AABB;)Z")) private boolean isVisible(Frustum frustum, AABB aABB) { - if(Initializer.CONFIG.entityCulling) { + if (Initializer.CONFIG.entityCulling) { WorldRenderer worldRenderer = WorldRenderer.getInstance(); Vec3 pos = aABB.getCenter(); RenderSection section = worldRenderer.getSectionGrid().getSectionAtBlockPos((int) pos.x(), (int) pos.y(), (int) pos.z()); - if(section == null) + if (section == null) return frustum.isVisible(aABB); return worldRenderer.getLastFrame() == section.getLastFrame(); @@ -57,4 +57,4 @@ private boolean isVisible(Frustum frustum, AABB aABB) { } } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java b/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java deleted file mode 100644 index 30b9f3194..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/entity/LevelRendererM.java +++ /dev/null @@ -1,104 +0,0 @@ -package net.vulkanmod.mixin.render.entity; - -import com.mojang.blaze3d.vertex.PoseStack; -import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import net.minecraft.client.Camera; -import net.minecraft.client.DeltaTracker; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.LevelRenderer; -import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.entity.EntityRenderDispatcher; -import net.minecraft.util.Mth; -import net.minecraft.world.TickRateManager; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.phys.Vec3; -import net.vulkanmod.Initializer; -import net.vulkanmod.render.chunk.WorldRenderer; -import org.joml.Matrix4f; -import org.spongepowered.asm.mixin.*; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.Map; - -@Mixin(LevelRenderer.class) -public class LevelRendererM { - - @Shadow @Final private EntityRenderDispatcher entityRenderDispatcher; - @Shadow @Final private Minecraft minecraft; - - @Unique private Object2ReferenceOpenHashMap, ObjectArrayList>> bufferSourceMap = new Object2ReferenceOpenHashMap<>(); - @Unique boolean managed; - - @Inject(method = "renderLevel", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/LevelRenderer;setupRender(Lnet/minecraft/client/Camera;Lnet/minecraft/client/renderer/culling/Frustum;ZZ)V", - shift = At.Shift.AFTER) - ) - private void clearMap(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { - for (var bufferSource : this.bufferSourceMap.keySet()) { - var entityMap = this.bufferSourceMap.get(bufferSource); - entityMap.clear(); - } - - this.managed = true; - } - - /** - * @author - * @reason - */ - @Overwrite - private void renderEntity(Entity entity, double d, double e, double f, float partialTicks, PoseStack poseStack, MultiBufferSource multiBufferSource) { - if (!Initializer.CONFIG.entityCulling || !this.managed) { - double h = Mth.lerp(partialTicks, entity.xOld, entity.getX()); - double i = Mth.lerp(partialTicks, entity.yOld, entity.getY()); - double j = Mth.lerp(partialTicks, entity.zOld, entity.getZ()); - float k = Mth.lerp(partialTicks, entity.yRotO, entity.getYRot()); - this.entityRenderDispatcher.render(entity, h - d, i - e, j - f, k, partialTicks, poseStack, multiBufferSource, this.entityRenderDispatcher.getPackedLightCoords(entity, partialTicks)); - return; - } - - var entityClass = entity.getClass(); - - var entityMap = this.bufferSourceMap.computeIfAbsent(multiBufferSource, bufferSource -> new Object2ReferenceOpenHashMap<>()); - var list = entityMap.computeIfAbsent(entityClass, k -> new ObjectArrayList<>()); - list.add(entity); - } - - @Inject(method = "renderLevel", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;endLastBatch()V", - shift = At.Shift.AFTER, ordinal = 0) - ) - private void renderEntities(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { - if (!Initializer.CONFIG.entityCulling) - return; - - Vec3 cameraPos = WorldRenderer.getCameraPos(); - TickRateManager tickRateManager = this.minecraft.level.tickRateManager(); - - PoseStack poseStack = new PoseStack(); - - for (var bufferSource : this.bufferSourceMap.keySet()) { - var entityMap = this.bufferSourceMap.get(bufferSource); - - for (var list : entityMap.values()) { - for (Entity entity : list) { - float partialTicks = deltaTracker.getGameTimeDeltaPartialTick(!tickRateManager.isEntityFrozen(entity)); - - double h = Mth.lerp(partialTicks, entity.xOld, entity.getX()); - double i = Mth.lerp(partialTicks, entity.yOld, entity.getY()); - double j = Mth.lerp(partialTicks, entity.zOld, entity.getZ()); - float k = Mth.lerp(partialTicks, entity.yRotO, entity.getYRot()); - this.entityRenderDispatcher.render(entity, h - cameraPos.x, i - cameraPos.y, j - cameraPos.z, k, partialTicks, poseStack, bufferSource, this.entityRenderDispatcher.getPackedLightCoords(entity, partialTicks)); - } - } - } - - this.managed = false; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartCubeM.java b/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartCubeM.java deleted file mode 100644 index fdc8fe213..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartCubeM.java +++ /dev/null @@ -1,34 +0,0 @@ -package net.vulkanmod.mixin.render.entity.model; - -import net.minecraft.client.model.geom.ModelPart; -import net.minecraft.core.Direction; -import net.vulkanmod.interfaces.ModelPartCubeMixed; -import net.vulkanmod.render.model.CubeModel; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.Set; - -@Mixin(ModelPart.Cube.class) -public class ModelPartCubeM implements ModelPartCubeMixed { - - CubeModel cube; - - @Inject(method = "", at = @At(value = "FIELD", - target = "Lnet/minecraft/client/model/geom/ModelPart$Cube;polygons:[Lnet/minecraft/client/model/geom/ModelPart$Polygon;", - ordinal = 0, shift = At.Shift.AFTER)) - private void getVertices(int i, int j, float f, float g, float h, float k, float l, float m, float n, float o, float p, boolean bl, float q, float r, Set set, CallbackInfo ci) { - //TODO check if set is needed - CubeModel cube = new CubeModel(); - cube.setVertices(i, j, f, g, h, k, l, m, n, o, p, bl, q, r, set); - this.cube = cube; - } - - - @Override - public CubeModel getCubeModel() { - return this.cube; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java b/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java deleted file mode 100644 index ecb2ffe27..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/entity/model/ModelPartM.java +++ /dev/null @@ -1,91 +0,0 @@ -package net.vulkanmod.mixin.render.entity.model; - -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.minecraft.client.model.geom.ModelPart; -import net.vulkanmod.interfaces.ExtendedVertexBuilder; -import net.vulkanmod.interfaces.ModelPartCubeMixed; -import net.vulkanmod.render.model.CubeModel; -import net.vulkanmod.render.vertex.format.I32_SNorm; -import net.vulkanmod.vulkan.util.ColorUtil; -import org.joml.Matrix3f; -import org.joml.Matrix4f; -import org.joml.Vector3f; -import org.spongepowered.asm.mixin.*; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.List; - -@Mixin(ModelPart.class) -public abstract class ModelPartM { - @Shadow @Final private List cubes; - - Vector3f normal = new Vector3f(); - - @Inject(method = "compile", at = @At("HEAD"), cancellable = true) - private void injCompile(PoseStack.Pose pose, VertexConsumer vertexConsumer, int light, int overlay, int color, CallbackInfo ci) { - this.renderCubes(pose, vertexConsumer, light, overlay, color); - ci.cancel(); - } - - @Unique - public void renderCubes(PoseStack.Pose pose, VertexConsumer vertexConsumer, int light, int overlay, int color) { - Matrix4f matrix4f = pose.pose(); - Matrix3f matrix3f = pose.normal(); - - ExtendedVertexBuilder vertexBuilder = ExtendedVertexBuilder.of(vertexConsumer); - - if (vertexBuilder != null && vertexBuilder.canUseFastVertex()) { - color = ColorUtil.RGBA.fromArgb32(color); - - for (ModelPart.Cube cube : this.cubes) { - ModelPartCubeMixed cubeMixed = (ModelPartCubeMixed)(cube); - CubeModel cubeModel = cubeMixed.getCubeModel(); - - ModelPart.Polygon[] polygons = cubeModel.getPolygons(); - - cubeModel.transformVertices(matrix4f); - - for (ModelPart.Polygon polygon : polygons) { - matrix3f.transform(this.normal.set(polygon.normal)); - this.normal.normalize(); - - int packedNormal = I32_SNorm.packNormal(normal.x(), normal.y(), normal.z()); - - ModelPart.Vertex[] vertices = polygon.vertices; - - for (ModelPart.Vertex vertex : vertices) { - Vector3f pos = vertex.pos; - vertexBuilder.vertex(pos.x(), pos.y(), pos.z(), color, vertex.u, vertex.v, overlay, light, packedNormal); - } - } - } - } - else { - for (ModelPart.Cube cube : this.cubes) { - ModelPartCubeMixed cubeMixed = (ModelPartCubeMixed)(cube); - CubeModel cubeModel = cubeMixed.getCubeModel(); - - ModelPart.Polygon[] polygons = cubeModel.getPolygons(); - - cubeModel.transformVertices(matrix4f); - - for (ModelPart.Polygon polygon : polygons) { - matrix3f.transform(this.normal.set(polygon.normal)); - this.normal.normalize(); - - ModelPart.Vertex[] vertices = polygon.vertices; - - for (ModelPart.Vertex vertex : vertices) { - Vector3f pos = vertex.pos; - vertexConsumer.addVertex(pos.x(), pos.y(), pos.z(), color, vertex.u, vertex.v, overlay, light, - normal.x(), normal.y(), normal.z()); - } - } - } - } - - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/frame/FramerateLimitTrackerMixin.java b/src/main/java/net/vulkanmod/mixin/render/frame/FramerateLimitTrackerMixin.java new file mode 100644 index 000000000..08c9ce943 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frame/FramerateLimitTrackerMixin.java @@ -0,0 +1,24 @@ +package net.vulkanmod.mixin.render.frame; + +import com.mojang.blaze3d.platform.FramerateLimitTracker; +import net.minecraft.client.Minecraft; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(FramerateLimitTracker.class) +public abstract class FramerateLimitTrackerMixin { + @Shadow + @Final + private Minecraft minecraft; + + @Inject(method = "getFramerateLimit", at = @At("HEAD"), cancellable = true) + private void vulkanmod$limitWhenMinimized(CallbackInfoReturnable cir) { + if (this.minecraft.noRender) { + cir.setReturnValue(10); + } + } +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java index 6184f7902..d59941188 100644 --- a/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/frame/MinecraftMixin.java @@ -1,7 +1,8 @@ package net.vulkanmod.mixin.render.frame; import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.systems.CommandEncoder; +import com.mojang.blaze3d.textures.GpuTexture; import net.minecraft.client.Minecraft; import net.vulkanmod.vulkan.Renderer; import org.spongepowered.asm.mixin.Mixin; @@ -10,22 +11,27 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(Minecraft.class) public class MinecraftMixin { - @Shadow public boolean noRender; + @Shadow + public boolean noRender; @Inject(method = "runTick", at = @At(value = "HEAD")) private void preFrameOps(boolean bl, CallbackInfo ci) { Renderer.getInstance().preInitFrame(); } - // Main target (framebuffer) ops - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;clear(IZ)V")) - private void beginRender(int i, boolean bl) { - RenderSystem.clear(i, bl); + @Redirect( + method = "runTick", + at = @At( + value = "INVOKE", + target = "Lcom/mojang/blaze3d/systems/CommandEncoder;clearColorAndDepthTextures(Lcom/mojang/blaze3d/textures/GpuTexture;ILcom/mojang/blaze3d/textures/GpuTexture;D)V" + ), + remap = false + ) + private void vulkanmod$skipMainTargetClear(CommandEncoder encoder, GpuTexture color, int level, GpuTexture depth, double depthValue) { Renderer.getInstance().beginFrame(); } @@ -34,18 +40,8 @@ private void beginRender2(CallbackInfo ci) { Renderer.getInstance().beginFrame(); } - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;bindWrite(Z)V")) - private void redirectMainTarget1(RenderTarget instance, boolean bl) { - Renderer.getInstance().getMainPass().mainTargetBindWrite(); - } - - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;unbindWrite()V")) - private void redirectMainTarget2(RenderTarget instance) { - Renderer.getInstance().getMainPass().mainTargetUnbindWrite(); - } - - @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;blitToScreen(II)V")) - private void removeBlit(RenderTarget instance, int i, int j) { + @Redirect(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;blitToScreen()V")) + private void vulkanmod$skipBlit(RenderTarget renderTarget) { } @@ -53,9 +49,4 @@ private void removeBlit(RenderTarget instance, int i, int j) { private void removeThreadYield() { } - @Inject(method = "getFramerateLimit", at = @At("HEAD"), cancellable = true) - private void limitWhenMinimized(CallbackInfoReturnable cir) { - if (this.noRender) - cir.setReturnValue(10); - } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/render/frame/RenderSystemMixin.java b/src/main/java/net/vulkanmod/mixin/render/frame/RenderSystemMixin.java index f4ca167b9..04aca31fc 100644 --- a/src/main/java/net/vulkanmod/mixin/render/frame/RenderSystemMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/frame/RenderSystemMixin.java @@ -1,13 +1,41 @@ package net.vulkanmod.mixin.render.frame; +import com.mojang.blaze3d.shaders.ShaderType; +import com.mojang.blaze3d.systems.GpuDevice; import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.renderer.DynamicUniforms; +import net.minecraft.resources.ResourceLocation; import net.vulkanmod.vulkan.Renderer; +import net.vulkanmod.vulkan.blaze.VulkanGpuDevice; +import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; +import java.util.function.BiFunction; + @Mixin(RenderSystem.class) -public class RenderSystemMixin { +public abstract class RenderSystemMixin { + + @Shadow @Nullable private static GpuDevice DEVICE; + @Shadow private static String apiDescription; + @Shadow @Nullable private static DynamicUniforms dynamicUniforms; + + /** + * Replace Mojang's GL device bootstrap with our Vulkan-backed implementation. + */ + @Overwrite(remap = false) + public static void initRenderer(long window, + int debugVerbosity, + boolean debugSync, + BiFunction shaderSourceGetter, + boolean enableDebugLabels) { + DEVICE = new VulkanGpuDevice(window, debugVerbosity, debugSync, shaderSourceGetter, enableDebugLabels); + apiDescription = DEVICE.getImplementationInformation(); + dynamicUniforms = new DynamicUniforms(); + } @Redirect(method = "flipFrame", at = @At(value = "INVOKE", target = "Lorg/lwjgl/glfw/GLFW;glfwSwapBuffers(J)V"), remap = false) private static void endFrame(long window) { diff --git a/src/main/java/net/vulkanmod/mixin/render/frame/TimerQueryMixin.java b/src/main/java/net/vulkanmod/mixin/render/frame/TimerQueryMixin.java new file mode 100644 index 000000000..0943a5953 --- /dev/null +++ b/src/main/java/net/vulkanmod/mixin/render/frame/TimerQueryMixin.java @@ -0,0 +1,29 @@ +package net.vulkanmod.mixin.render.frame; + +import com.mojang.blaze3d.systems.TimerQuery; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(TimerQuery.class) +public class TimerQueryMixin { + + @Inject(method = "beginProfile", at = @At("HEAD"), cancellable = true) + private void vulkanmod$skipBegin(CallbackInfo ci) { + ci.cancel(); + } + + @Inject(method = "endProfile", at = @At("HEAD"), cancellable = true) + private void vulkanmod$skipEnd(CallbackInfoReturnable cir) { + cir.setReturnValue(null); + cir.cancel(); + } + + @Inject(method = "isRecording", at = @At("HEAD"), cancellable = true) + private void vulkanmod$skipRecording(CallbackInfoReturnable cir) { + cir.setReturnValue(false); + cir.cancel(); + } +} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java deleted file mode 100644 index b8decdc33..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/BakedModelM.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.vulkanmod.mixin.render.frapi; - -import net.fabricmc.fabric.api.renderer.v1.model.FabricBakedModel; -import net.fabricmc.fabric.api.renderer.v1.render.RenderContext; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.vulkanmod.render.chunk.build.frapi.render.AbstractBlockRenderContext; -import net.vulkanmod.render.chunk.build.frapi.render.ItemRenderContext; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.function.Supplier; - -@Mixin(BakedModel.class) -public interface BakedModelM extends FabricBakedModel { - - @Override - default void emitBlockQuads(BlockAndTintGetter blockView, BlockState state, BlockPos pos, Supplier randomSupplier, RenderContext context) { - ((AbstractBlockRenderContext) context).emitBlockQuads((BakedModel) this, state, randomSupplier, context); - } - - @Override - default void emitItemQuads(ItemStack stack, Supplier randomSupplier, RenderContext context) { - ((ItemRenderContext) context).emitItemQuads((BakedModel) this, null, randomSupplier); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java deleted file mode 100644 index 1eca3abcf..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererAccessor.java +++ /dev/null @@ -1,14 +0,0 @@ -package net.vulkanmod.mixin.render.frapi; - -import net.minecraft.client.renderer.entity.ItemRenderer; -import net.minecraft.world.item.ItemStack; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; - -@Mixin(ItemRenderer.class) -public interface ItemRendererAccessor { - @Invoker("hasAnimatedTexture") - static boolean hasAnimatedTexture(ItemStack stack) { - throw new AssertionError(); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java deleted file mode 100644 index 5ab645091..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/ItemRendererMixin.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.mixin.render.frapi; - -import net.vulkanmod.render.chunk.build.frapi.render.ItemRenderContext; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import net.minecraft.client.color.item.ItemColors; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.entity.ItemRenderer; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.item.ItemStack; -import com.mojang.blaze3d.vertex.PoseStack; - -@Mixin(ItemRenderer.class) -public abstract class ItemRendererMixin { - @Final - @Shadow - private ItemColors itemColors; - - @Unique - private final ThreadLocal fabric_contexts = ThreadLocal.withInitial(() -> new ItemRenderContext(itemColors)); - - @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/client/resources/model/BakedModel;isCustomRenderer()Z"), method = "render", cancellable = true) - public void hook_renderItem(ItemStack stack, ItemDisplayContext transformMode, boolean invert, PoseStack matrixStack, MultiBufferSource vertexConsumerProvider, int light, int overlay, BakedModel model, CallbackInfo ci) { - if (!model.isVanillaAdapter()) { - fabric_contexts.get().renderModel(stack, transformMode, invert, matrixStack, vertexConsumerProvider, light, overlay, model); - matrixStack.popPose(); - ci.cancel(); - } - } -} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java b/src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java deleted file mode 100644 index d89759594..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/frapi/ModelBlockRendererM.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.mixin.render.frapi; - -import net.vulkanmod.render.chunk.build.frapi.render.BlockRenderContext; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.minecraft.client.renderer.block.ModelBlockRenderer; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; - -@Mixin(ModelBlockRenderer.class) -public abstract class ModelBlockRendererM { - - // TODO ThreadLocal look ups are slow, same goes for ItemRendererMixin - @Unique - private final ThreadLocal fabric_contexts = ThreadLocal.withInitial(BlockRenderContext::new); - - @Inject(at = @At("HEAD"), method = "tesselateBlock", cancellable = true) - private void hookRender(BlockAndTintGetter blockView, BakedModel model, BlockState state, BlockPos pos, PoseStack matrix, VertexConsumer buffer, boolean cull, RandomSource rand, long seed, int overlay, CallbackInfo ci) { - if (!model.isVanillaAdapter()) { - BlockRenderContext context = fabric_contexts.get(); - context.render(blockView, model, state, pos, matrix, buffer, cull, rand, seed, overlay); - ci.cancel(); - } - } - -} diff --git a/src/main/java/net/vulkanmod/mixin/render/particle/SingleQuadParticleM.java b/src/main/java/net/vulkanmod/mixin/render/particle/SingleQuadParticleM.java index 220b9235d..51911a2b2 100644 --- a/src/main/java/net/vulkanmod/mixin/render/particle/SingleQuadParticleM.java +++ b/src/main/java/net/vulkanmod/mixin/render/particle/SingleQuadParticleM.java @@ -13,7 +13,6 @@ import net.vulkanmod.interfaces.ExtendedVertexBuilder; import net.vulkanmod.render.chunk.RenderSection; import net.vulkanmod.render.chunk.WorldRenderer; -import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.util.ColorUtil; import org.joml.Quaternionf; import org.joml.Vector3f; @@ -25,25 +24,48 @@ @Mixin(SingleQuadParticle.class) public abstract class SingleQuadParticleM extends Particle { - @Shadow protected float quadSize; - - @Unique private final Quaternionf quaternionf = new Quaternionf(); - @Unique private final Vector3f vector3f = new Vector3f(); - - @Shadow protected abstract float getU0(); - @Shadow protected abstract float getU1(); - @Shadow protected abstract float getV0(); - @Shadow protected abstract float getV1(); - - @Shadow public abstract float getQuadSize(float f); - - @Shadow public abstract SingleQuadParticle.FacingCameraMode getFacingCameraMode(); + @Unique + private final Quaternionf quaternionf = new Quaternionf(); + @Unique + private final Vector3f vector3f = new Vector3f(); + @Shadow + protected float quadSize; + @Shadow + protected float rCol; + @Shadow + protected float gCol; + @Shadow + protected float bCol; + @Shadow + protected float alpha; + @Shadow + protected float roll; + @Shadow + protected float oRoll; protected SingleQuadParticleM(ClientLevel clientLevel, double d, double e, double f, double g, double h, double i) { super(clientLevel, d, e, f, g, h, i); this.quadSize = 0.1F * (this.random.nextFloat() * 0.5F + 0.5F) * 2.0F; } + @Shadow + protected abstract float getU0(); + + @Shadow + protected abstract float getU1(); + + @Shadow + protected abstract float getV0(); + + @Shadow + protected abstract float getV1(); + + @Shadow + public abstract float getQuadSize(float f); + + @Shadow + public abstract SingleQuadParticle.FacingCameraMode getFacingCameraMode(); + /** * @author * @reason @@ -80,12 +102,12 @@ private void renderRotatedQuad(VertexConsumer vertexConsumer, Quaternionf quater float v1 = this.getV1(); int light = this.getLightColor(f); - ExtendedVertexBuilder vertexBuilder = (ExtendedVertexBuilder)vertexConsumer; + ExtendedVertexBuilder vertexBuilder = (ExtendedVertexBuilder) vertexConsumer; int packedColor = ColorUtil.RGBA.pack(this.rCol, this.gCol, this.bCol, this.alpha); - this.renderVertex(vertexBuilder, quaternionf, x, y, z, 1.0F, -1.0F, j, u1, v1, packedColor, light); - this.renderVertex(vertexBuilder, quaternionf, x, y, z, 1.0F, 1.0F, j, u1, v0, packedColor, light); - this.renderVertex(vertexBuilder, quaternionf, x, y, z, -1.0F, 1.0F, j, u0, v0, packedColor, light); + this.renderVertex(vertexBuilder, quaternionf, x, y, z, 1.0F, -1.0F, j, u1, v1, packedColor, light); + this.renderVertex(vertexBuilder, quaternionf, x, y, z, 1.0F, 1.0F, j, u1, v0, packedColor, light); + this.renderVertex(vertexBuilder, quaternionf, x, y, z, -1.0F, 1.0F, j, u0, v0, packedColor, light); this.renderVertex(vertexBuilder, quaternionf, x, y, z, -1.0F, -1.0F, j, u0, v1, packedColor, light); } @@ -111,8 +133,12 @@ private boolean cull(WorldRenderer worldRenderer, double x, double y, double z) return section != null && section.getLastFrame() != worldRenderer.getLastFrame(); } - @Override - public ParticleRenderType getRenderType() { - return null; + /** + * @author + * @reason Prevent vanilla from queuing the default quad renderer – Vulkan handles rendering directly in {@link #render}. + */ + @Overwrite + public ParticleRenderType getGroup() { + return ParticleRenderType.NO_RENDER; } } diff --git a/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java b/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java deleted file mode 100644 index 61adacc7c..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/target/MainTargetMixin.java +++ /dev/null @@ -1,46 +0,0 @@ -package net.vulkanmod.mixin.render.target; - -import com.mojang.blaze3d.pipeline.MainTarget; -import com.mojang.blaze3d.pipeline.RenderTarget; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.Vulkan; -import net.vulkanmod.vulkan.framebuffer.SwapChain; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -@Mixin(MainTarget.class) -public class MainTargetMixin extends RenderTarget { - - public MainTargetMixin(boolean useDepth) { - super(useDepth); - } - - /** - * @author - * @reason - */ - @Overwrite - private void createFrameBuffer(int width, int height) { - this.frameBufferId = 0; - - this.viewWidth = width; - this.viewHeight = height; - this.width = width; - this.height = height; - } - - @Override - public void bindWrite(boolean updateScissor) { - Renderer.getInstance().getMainPass().rebindMainTarget(); - } - - @Override - public void bindRead() { - Renderer.getInstance().getMainPass().bindAsTexture(); - } - - @Override - public int getColorTextureId() { - return Renderer.getInstance().getMainPass().getColorAttachment().id; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java b/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java deleted file mode 100644 index 4579ba83c..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/target/RenderTargetMixin.java +++ /dev/null @@ -1,155 +0,0 @@ -package net.vulkanmod.mixin.render.target; - -import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.systems.RenderSystem; -import net.vulkanmod.gl.VkGlFramebuffer; -import net.vulkanmod.gl.VkGlTexture; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.framebuffer.Framebuffer; -import net.vulkanmod.vulkan.texture.VTextureSelector; -import net.vulkanmod.vulkan.util.DrawUtil; -import org.lwjgl.opengl.GL30; -import org.lwjgl.system.MemoryStack; -import org.spongepowered.asm.mixin.*; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(RenderTarget.class) -public abstract class RenderTargetMixin { - - @Shadow public int viewWidth; - @Shadow public int viewHeight; - @Shadow public int width; - @Shadow public int height; - - @Shadow protected int depthBufferId; - @Shadow protected int colorTextureId; - @Shadow public int frameBufferId; - - @Shadow @Final private float[] clearChannels; - @Shadow @Final public boolean useDepth; - - boolean needClear = false; - boolean bound = false; - - /** - * @author - */ - @Overwrite - public void clear(boolean getError) { - RenderSystem.assertOnRenderThreadOrInit(); - - if(!Renderer.isRecording()) - return; - - // If the framebuffer is not bound postpone clear - VkGlFramebuffer glFramebuffer = VkGlFramebuffer.getFramebuffer(this.frameBufferId); - if(!bound || VkGlFramebuffer.getBoundFramebuffer() != glFramebuffer) { - needClear = true; - return; - } - - GlStateManager._clearColor(this.clearChannels[0], this.clearChannels[1], this.clearChannels[2], this.clearChannels[3]); - int i = 16384; - if (this.useDepth) { - GlStateManager._clearDepth(1.0); - i |= 256; - } - - GlStateManager._clear(i, getError); - needClear = false; - } - - /** - * @author - */ - @Overwrite - public void bindRead() { - RenderSystem.assertOnRenderThread(); - - applyClear(); - - VkGlTexture.bindTexture(this.colorTextureId); - - try (MemoryStack stack = MemoryStack.stackPush()) { - VkGlTexture.getBoundTexture().getVulkanImage() - .readOnlyLayout(stack, Renderer.getCommandBuffer()); - } - } - - /** - * @author - */ - @Overwrite - public void unbindRead() { - RenderSystem.assertOnRenderThreadOrInit(); - VkGlTexture.bindTexture(0); - } - - /** - * @author - */ - @Overwrite - private void _bindWrite(boolean bl) { - RenderSystem.assertOnRenderThreadOrInit(); - - VkGlFramebuffer.bindFramebuffer(GL30.GL_FRAMEBUFFER, this.frameBufferId); - if (bl) { - GlStateManager._viewport(0, 0, this.viewWidth, this.viewHeight); - } - - this.bound = true; - if (needClear) - clear(false); - } - - /** - * @author - */ - @Overwrite - public void unbindWrite() { - if (!RenderSystem.isOnRenderThread()) { - RenderSystem.recordRenderCall(() -> { - GlStateManager._glBindFramebuffer(36160, 0); - this.bound = false; - }); - } else { - GlStateManager._glBindFramebuffer(36160, 0); - this.bound = false; - } - } - - @Inject(method = "_blitToScreen", at = @At("HEAD"), cancellable = true) - private void _blitToScreen(int width, int height, boolean disableBlend, CallbackInfo ci) { - // If the target needs clear it means it has not been used, thus we can skip blit - if (!this.needClear) { - Framebuffer framebuffer = VkGlFramebuffer.getFramebuffer(this.frameBufferId).getFramebuffer(); - VTextureSelector.bindTexture(0, framebuffer.getColorAttachment()); - - DrawUtil.blitToScreen(); - } - - ci.cancel(); - } - - @Inject(method = "getColorTextureId", at = @At("HEAD")) - private void injClear(CallbackInfoReturnable cir) { - applyClear(); - } - - @Unique - private void applyClear() { - if (this.needClear) { - VkGlFramebuffer currentFramebuffer = VkGlFramebuffer.getBoundFramebuffer(); - - this._bindWrite(false); - - if (currentFramebuffer != null) { - VkGlFramebuffer.beginRendering(currentFramebuffer); - } - } - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java index a7e5c696e..7073e4dfa 100644 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java +++ b/src/main/java/net/vulkanmod/mixin/render/vertex/BufferBuilderM.java @@ -2,7 +2,7 @@ import com.mojang.blaze3d.vertex.*; import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.core.Vec3i; +import net.minecraft.core.Direction; import net.vulkanmod.interfaces.ExtendedVertexBuilder; import net.vulkanmod.mixin.matrix.PoseAccessor; import net.vulkanmod.render.util.MathUtil; @@ -16,18 +16,24 @@ public abstract class BufferBuilderM implements VertexConsumer, ExtendedVertexBuilder { - @Shadow private boolean fastFormat; - @Shadow private boolean fullFormat; - @Shadow private VertexFormat format; - - @Shadow protected abstract long beginVertex(); - - @Shadow private int elementsToFill; - @Shadow @Final private int initialElementsToFill; + @Shadow + private boolean fastFormat; + @Shadow + private boolean fullFormat; + @Shadow + private VertexFormat format; + @Shadow + private int elementsToFill; + @Shadow + @Final + private int initialElementsToFill; + private long ptr; - @Shadow protected abstract long beginElement(VertexFormatElement vertexFormatElement); + @Shadow + protected abstract long beginVertex(); - private long ptr; + @Shadow + protected abstract long beginElement(VertexFormatElement vertexFormatElement); public void vertex(float x, float y, float z, int packedColor, float u, float v, int overlay, int light, int packedNormal) { this.ptr = this.beginVertex(); @@ -47,8 +53,7 @@ public void vertex(float x, float y, float z, int packedColor, float u, float v, MemoryUtil.memPutInt(ptr + 28, light); MemoryUtil.memPutInt(ptr + 32, packedNormal); - } - else { + } else { this.elementsToFill = this.initialElementsToFill; this.position(x, y, z); @@ -162,12 +167,15 @@ public void putBulkData(PoseStack.Pose matrixEntry, BakedQuad quad, float[] brig @SuppressWarnings("UnreachableCode") @Unique private void putQuadData(PoseStack.Pose matrixEntry, BakedQuad quad, float[] brightness, float red, float green, float blue, float alpha, int[] lights, int overlay, boolean useQuadColorData) { - int[] quadData = quad.getVertices(); - Vec3i vec3i = quad.getDirection().getNormal(); + int[] quadData = quad.vertices(); + Direction direction = quad.direction(); + int normalX = direction.getStepX(); + int normalY = direction.getStepY(); + int normalZ = direction.getStepZ(); Matrix4f matrix4f = matrixEntry.pose(); - boolean trustedNormals = ((PoseAccessor)(Object)matrixEntry).trustedNormals(); - int normal = MathUtil.packTransformedNorm(matrixEntry.normal(), trustedNormals, vec3i.getX(), vec3i.getY(), vec3i.getZ()); + boolean trustedNormals = ((PoseAccessor) (Object) matrixEntry).trustedNormals(); + int normal = MathUtil.packTransformedNorm(matrixEntry.normal(), trustedNormals, normalX, normalY, normalZ); for (int k = 0; k < 4; ++k) { float r, g, b; diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/FaceBakeryM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/FaceBakeryM.java deleted file mode 100644 index b3262bb89..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/FaceBakeryM.java +++ /dev/null @@ -1,80 +0,0 @@ -package net.vulkanmod.mixin.render.vertex; - -import com.mojang.math.*; -import net.minecraft.client.renderer.FaceInfo; -import net.minecraft.client.renderer.block.model.BlockFaceUV; -import net.minecraft.client.renderer.block.model.FaceBakery; -import net.minecraft.core.BlockMath; -import net.minecraft.core.Direction; -import net.minecraft.util.Mth; -import org.joml.Matrix3f; -import org.joml.Matrix4f; -import org.joml.Vector3f; -import org.joml.Vector4f; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -@Mixin(FaceBakery.class) -public class FaceBakeryM { - - private static final float DIV = 1.0f / 16.0f; - private static final double DIV_2 = 1.0 / 90.0; - - /** - * @author - */ - @Overwrite - private float[] setupShape(Vector3f vector3f, Vector3f vector3f2) { - float[] fs = new float[Direction.values().length]; - fs[FaceInfo.Constants.MIN_X] = vector3f.x() * DIV; - fs[FaceInfo.Constants.MIN_Y] = vector3f.y() * DIV; - fs[FaceInfo.Constants.MIN_Z] = vector3f.z() * DIV; - fs[FaceInfo.Constants.MAX_X] = vector3f2.x() * DIV; - fs[FaceInfo.Constants.MAX_Y] = vector3f2.y() * DIV; - fs[FaceInfo.Constants.MAX_Z] = vector3f2.z() * DIV; - return fs; - } - - /** - * @author - */ - @Overwrite - public static BlockFaceUV recomputeUVs(BlockFaceUV blockFaceUV, Direction direction, Transformation transformation) { - Matrix4f matrix4f = BlockMath.getUVLockTransform(transformation, direction).getMatrix(); - float f = blockFaceUV.getU(blockFaceUV.getReverseIndex(0)); - float g = blockFaceUV.getV(blockFaceUV.getReverseIndex(0)); - Vector4f vector4f = matrix4f.transform(new Vector4f(f * DIV, g * DIV, 0.0F, 1.0F)); - float h = 16.0F * vector4f.x(); - float i = 16.0F * vector4f.y(); - float j = blockFaceUV.getU(blockFaceUV.getReverseIndex(2)); - float k = blockFaceUV.getV(blockFaceUV.getReverseIndex(2)); - Vector4f vector4f2 = matrix4f.transform(new Vector4f(j * DIV, k * DIV, 0.0F, 1.0F)); - float l = 16.0F * vector4f2.x(); - float m = 16.0F * vector4f2.y(); - float n; - float o; - if (Math.signum(j - f) == Math.signum(l - h)) { - n = h; - o = l; - } else { - n = l; - o = h; - } - - float p; - float q; - if (Math.signum(k - g) == Math.signum(m - i)) { - p = i; - q = m; - } else { - p = m; - q = i; - } - - float r = (float)Math.toRadians(blockFaceUV.rotation); - Matrix3f matrix3f = new Matrix3f(matrix4f); - Vector3f vector3f = matrix3f.transform(new Vector3f(Mth.cos(r), Mth.sin(r), 0.0F)); - int s = Math.floorMod(-((int)Math.round(Math.toDegrees(Math.atan2(vector3f.y(), vector3f.x())) * DIV_2)) * 90, 360); - return new BlockFaceUV(new float[]{n, p, o, q}, s); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java b/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java deleted file mode 100644 index e355ccadd..000000000 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexBufferM.java +++ /dev/null @@ -1,87 +0,0 @@ -package net.vulkanmod.mixin.render.vertex; - -import com.mojang.blaze3d.vertex.ByteBufferBuilder; -import com.mojang.blaze3d.vertex.MeshData; -import com.mojang.blaze3d.vertex.VertexBuffer; -import net.minecraft.client.renderer.ShaderInstance; -import net.vulkanmod.render.VBO; -import org.joml.Matrix4f; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(VertexBuffer.class) -public class VertexBufferM { - - private VBO vbo; - - @Inject(method = "", at = @At("RETURN")) - private void constructor(VertexBuffer.Usage usage, CallbackInfo ci) { - vbo = new VBO(usage); - } - - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;_glGenBuffers()I")) - private int doNothing() { - return 0; - } - - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;_glGenVertexArrays()I")) - private int doNothing2() { - return 0; - } - - /** - * @author - */ - @Overwrite - public void bind() {} - - /** - * @author - */ - @Overwrite - public static void unbind() {} - - /** - * @author - */ - @Overwrite - public void upload(MeshData meshData) { - vbo.upload(meshData); - } - - /** - * @author - */ - @Overwrite - public void uploadIndexBuffer(ByteBufferBuilder.Result result) { - vbo.uploadIndexBuffer(result.byteBuffer()); - } - - /** - * @author - */ - @Overwrite - public void drawWithShader(Matrix4f viewMatrix, Matrix4f projectionMatrix, ShaderInstance shader) { - vbo.drawWithShader(viewMatrix, projectionMatrix, shader); - } - - /** - * @author - */ - @Overwrite - public void draw() { - vbo.draw(); - } - - /** - * @author - */ - @Overwrite - public void close() { - vbo.close(); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexFormatMixin.java b/src/main/java/net/vulkanmod/mixin/render/vertex/VertexFormatMixin.java index 0fef9b2e9..197bac277 100644 --- a/src/main/java/net/vulkanmod/mixin/render/vertex/VertexFormatMixin.java +++ b/src/main/java/net/vulkanmod/mixin/render/vertex/VertexFormatMixin.java @@ -1,14 +1,11 @@ package net.vulkanmod.mixin.render.vertex; -import com.google.common.collect.ImmutableMap; import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.blaze3d.vertex.VertexFormatElement; import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.vulkanmod.interfaces.VertexFormatMixed; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; diff --git a/src/main/java/net/vulkanmod/mixin/screen/OptionsScreenM.java b/src/main/java/net/vulkanmod/mixin/screen/OptionsScreenM.java index e3f20791b..5294a8857 100644 --- a/src/main/java/net/vulkanmod/mixin/screen/OptionsScreenM.java +++ b/src/main/java/net/vulkanmod/mixin/screen/OptionsScreenM.java @@ -15,9 +15,13 @@ @Mixin(OptionsScreen.class) public class OptionsScreenM extends Screen { - @Shadow @Final private Screen lastScreen; + @Shadow + @Final + private Screen lastScreen; - @Shadow @Final private Options options; + @Shadow + @Final + private Options options; protected OptionsScreenM(Component title) { super(title); diff --git a/src/main/java/net/vulkanmod/mixin/screen/ScreenM.java b/src/main/java/net/vulkanmod/mixin/screen/ScreenM.java index e41785636..98c81a496 100644 --- a/src/main/java/net/vulkanmod/mixin/screen/ScreenM.java +++ b/src/main/java/net/vulkanmod/mixin/screen/ScreenM.java @@ -1,5 +1,6 @@ package net.vulkanmod.mixin.screen; +import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.Screen; import net.vulkanmod.vulkan.Renderer; import org.spongepowered.asm.mixin.Mixin; @@ -11,7 +12,7 @@ public class ScreenM { @Inject(method = "renderBlurredBackground", at = @At("RETURN")) - private void clearDepth(float f, CallbackInfo ci) { + private void clearDepth(GuiGraphics guiGraphics, CallbackInfo ci) { // Workaround to fix hardcoded z value on PostPass blit shader, // that conflicts with Vulkan depth range [0.0, 1.0] Renderer.clearAttachments(256); diff --git a/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java b/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java deleted file mode 100644 index fa7a99ce5..000000000 --- a/src/main/java/net/vulkanmod/mixin/texture/MAbstractTexture.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.vulkanmod.mixin.texture; - -import com.mojang.blaze3d.systems.RenderSystem; -import net.minecraft.client.renderer.texture.AbstractTexture; -import net.vulkanmod.gl.VkGlTexture; -import net.vulkanmod.vulkan.texture.VulkanImage; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; - -@Mixin(AbstractTexture.class) -public abstract class MAbstractTexture { - @Shadow protected boolean blur; - @Shadow protected boolean mipmap; - - @Shadow protected int id; - - /** - * @author - */ - @Overwrite - public void bind() { - if (!RenderSystem.isOnRenderThreadOrInit()) { - RenderSystem.recordRenderCall(this::bindTexture); - } else { - this.bindTexture(); - } - } - - /** - * @author - */ - @Overwrite - public void setFilter(boolean blur, boolean mipmap) { - this.blur = blur; - this.mipmap = mipmap; - - VkGlTexture glTexture = VkGlTexture.getTexture(this.id); - VulkanImage vulkanImage = glTexture.getVulkanImage(); - - if (vulkanImage != null) - vulkanImage.updateTextureSampler(this.blur, false, this.mipmap); - } - - @Unique - private void bindTexture() { - VkGlTexture.bindTexture(this.id); - } -} diff --git a/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java b/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java deleted file mode 100644 index d04bc43ef..000000000 --- a/src/main/java/net/vulkanmod/mixin/texture/MTextureUtil.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.vulkanmod.mixin.texture; - -import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.platform.TextureUtil; -import com.mojang.blaze3d.systems.RenderSystem; -import net.vulkanmod.gl.VkGlTexture; -import net.vulkanmod.vulkan.texture.VTextureSelector; -import net.vulkanmod.vulkan.texture.VulkanImage; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL30; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Unique; - -import static org.lwjgl.vulkan.VK10.VK_FORMAT_R8G8B8A8_UNORM; -import static org.lwjgl.vulkan.VK10.VK_FORMAT_R8_UNORM; - -@Mixin(TextureUtil.class) -public class MTextureUtil { - - /** - * @author - */ - @Overwrite(remap = false) - public static int generateTextureId() { - RenderSystem.assertOnRenderThreadOrInit(); - return VkGlTexture.genTextureId(); - } - - /** - * @author - */ - @Overwrite(remap = false) - public static void prepareImage(NativeImage.InternalGlFormat internalGlFormat, int id, int mipLevels, int width, int height) { - RenderSystem.assertOnRenderThreadOrInit(); - VkGlTexture.bindTexture(id); - VkGlTexture glTexture = VkGlTexture.getBoundTexture(); - VulkanImage image = glTexture.getVulkanImage(); - - if (mipLevels > 0) { - GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL30.GL_TEXTURE_MAX_LEVEL, mipLevels); - GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL30.GL_TEXTURE_MIN_LOD, 0); - GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL30.GL_TEXTURE_MAX_LOD, mipLevels); - GlStateManager._texParameter(GL11.GL_TEXTURE_2D, GL30.GL_TEXTURE_LOD_BIAS, 0.0F); - } - - if (image == null || image.mipLevels != mipLevels || image.width != width || image.height != height) { - if (image != null) - image.free(); - - image = new VulkanImage.Builder(width, height) - .setName(String.format("Texture %d", id)) - .setMipLevels(mipLevels + 1) - .setFormat(convertFormat(internalGlFormat)) - .setLinearFiltering(false) - .setClamp(false) - .createVulkanImage(); - - glTexture.setVulkanImage(image); - VTextureSelector.bindTexture(image); - } - } - - @Unique - private static int convertFormat(NativeImage.InternalGlFormat format) { - return switch (format) { - case RGBA -> VK_FORMAT_R8G8B8A8_UNORM; - case RED -> VK_FORMAT_R8_UNORM; - default -> throw new IllegalArgumentException(String.format("Unxepcted format: %s", format)); - }; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java b/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java deleted file mode 100644 index 6eecb8cc3..000000000 --- a/src/main/java/net/vulkanmod/mixin/texture/image/MNativeImage.java +++ /dev/null @@ -1,109 +0,0 @@ -package net.vulkanmod.mixin.texture.image; - -import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.systems.RenderSystem; -import net.vulkanmod.vulkan.Renderer; -import net.vulkanmod.vulkan.texture.ImageUtil; -import net.vulkanmod.vulkan.texture.VTextureSelector; -import net.vulkanmod.vulkan.util.ColorUtil; -import org.lwjgl.system.MemoryUtil; -import org.lwjgl.vulkan.VK10; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.nio.ByteBuffer; -import java.util.Locale; - -@Mixin(NativeImage.class) -public abstract class MNativeImage { - - @Shadow private long pixels; - @Shadow private long size; - - @Shadow public abstract void close(); - - - @Shadow @Final private NativeImage.Format format; - - @Shadow public abstract int getWidth(); - - @Shadow @Final private int width; - @Shadow @Final private int height; - - @Shadow public abstract int getHeight(); - - @Shadow public abstract void setPixelRGBA(int i, int j, int k); - - @Shadow public abstract int getPixelRGBA(int i, int j); - - @Shadow protected abstract void checkAllocated(); - - private ByteBuffer buffer; - - @Inject(method = "(Lcom/mojang/blaze3d/platform/NativeImage$Format;IIZ)V", at = @At("RETURN")) - private void constr(NativeImage.Format format, int width, int height, boolean useStb, CallbackInfo ci) { - if(this.pixels != 0) { - buffer = MemoryUtil.memByteBuffer(this.pixels, (int)this.size); - } - } - - @Inject(method = "(Lcom/mojang/blaze3d/platform/NativeImage$Format;IIZJ)V", at = @At("RETURN")) - private void constr(NativeImage.Format format, int width, int height, boolean useStb, long pixels, CallbackInfo ci) { - if(this.pixels != 0) { - buffer = MemoryUtil.memByteBuffer(this.pixels, (int)this.size); - } - } - - /** - * @author - */ - @Overwrite - private void _upload(int level, int xOffset, int yOffset, int unpackSkipPixels, int unpackSkipRows, int widthIn, int heightIn, boolean blur, boolean clamp, boolean mipmap, boolean autoClose) { - RenderSystem.assertOnRenderThreadOrInit(); - - VTextureSelector.uploadSubTexture(level, widthIn, heightIn, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, this.getWidth(), this.buffer); - VTextureSelector.getBoundTexture().updateTextureSampler(blur, clamp, mipmap); - - if (autoClose) { - this.close(); - } - } - - /** - * @author - */ - @Overwrite - public void downloadTexture(int level, boolean removeAlpha) { - RenderSystem.assertOnRenderThread(); - - ImageUtil.downloadTexture(VTextureSelector.getBoundTexture(0), this.pixels); - - if (removeAlpha && this.format.hasAlpha()) { - if (this.format != NativeImage.Format.RGBA) { - throw new IllegalArgumentException(String.format(Locale.ROOT, "getPixelRGBA only works on RGBA images; have %s", this.format)); - } - - var colorAttachment = ( Renderer.getInstance() - .getMainPass() - .getColorAttachment()); - boolean isBGRAFormat = (colorAttachment.getVulkanImage().format == VK10.VK_FORMAT_B8G8R8A8_UNORM); - - for (long l = 0; l < this.width * this.height * 4L; l+=4) { - int v = MemoryUtil.memGetInt(this.pixels + l); - - if (isBGRAFormat) - v = ColorUtil.BGRAtoRGBA(v); - - v = v | 255 << this.format.alphaOffset(); - MemoryUtil.memPutInt(this.pixels + l, v); - } - } - - } - -} diff --git a/src/main/java/net/vulkanmod/mixin/texture/mip/MipmapGeneratorM.java b/src/main/java/net/vulkanmod/mixin/texture/mip/MipmapGeneratorM.java index 6f47b9740..cdbbd4dfc 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/mip/MipmapGeneratorM.java +++ b/src/main/java/net/vulkanmod/mixin/texture/mip/MipmapGeneratorM.java @@ -1,10 +1,8 @@ package net.vulkanmod.mixin.texture.mip; import com.mojang.blaze3d.platform.NativeImage; -import net.minecraft.Util; import net.minecraft.client.renderer.texture.MipmapGenerator; import net.vulkanmod.mixin.texture.image.NativeImageAccessor; -import org.lwjgl.opengl.GL30; import org.lwjgl.system.MemoryUtil; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -33,7 +31,7 @@ public static NativeImage[] generateMipLevels(NativeImage[] nativeImages, int i) NativeImage[] nativeImages2 = new NativeImage[i + 1]; nativeImages2[0] = nativeImages[0]; - long srcPtr = ((NativeImageAccessor)(Object)nativeImages2[0]).getPixels(); + long srcPtr = ((NativeImageAccessor) (Object) nativeImages2[0]).getPixels(); boolean bl = hasTransparentPixel(srcPtr, nativeImages2[0].getWidth(), nativeImages2[0].getHeight()); if (bl) { @@ -59,7 +57,7 @@ public static NativeImage[] generateMipLevels(NativeImage[] nativeImages, int i) } - for(int j = 1; j <= i; ++j) { + for (int j = 1; j <= i; ++j) { if (j < nativeImages.length) { nativeImages2[j] = nativeImages[j]; } else { @@ -68,12 +66,12 @@ public static NativeImage[] generateMipLevels(NativeImage[] nativeImages, int i) int width = nativeImage2.getWidth(); int height = nativeImage2.getHeight(); - srcPtr = ((NativeImageAccessor)(Object)nativeImage).getPixels(); - long dstPtr = ((NativeImageAccessor)(Object)nativeImage2).getPixels(); + srcPtr = ((NativeImageAccessor) (Object) nativeImage).getPixels(); + long dstPtr = ((NativeImageAccessor) (Object) nativeImage2).getPixels(); final int width2 = width * 2; - for(int m = 0; m < width; ++m) { - for(int n = 0; n < height; ++n) { + for (int m = 0; m < width; ++m) { + for (int n = 0; n < height; ++n) { int p0 = MemoryUtil.memGetInt(srcPtr + ((m * 2 + 0) + ((n * 2 + 0) * width2)) * 4L); int p1 = MemoryUtil.memGetInt(srcPtr + ((m * 2 + 1) + ((n * 2 + 0) * width2)) * 4L); int p2 = MemoryUtil.memGetInt(srcPtr + ((m * 2 + 0) + ((n * 2 + 1) * width2)) * 4L); @@ -93,8 +91,8 @@ public static NativeImage[] generateMipLevels(NativeImage[] nativeImages, int i) } private static boolean hasTransparentPixel(long ptr, int width, int height) { - for(int i = 0; i < width; ++i) { - for(int j = 0; j < height; ++j) { + for (int i = 0; i < width; ++i) { + for (int j = 0; j < height; ++j) { if (getPixelA(MemoryUtil.memGetInt(ptr + (i + j * width) * 4L)) == 0) { return true; } @@ -122,8 +120,8 @@ private static int gammaBlend(int i, int j, int k, int l, int m) { float g = getPow22(j >> m); float h = getPow22(k >> m); float n = getPow22(l >> m); - float o = (float)((double)((float)Math.pow((double)(f + g + h + n) * 0.25, 0.45454545454545453))); - return (int)((double)o * 255.0); + float o = (float) ((double) ((float) Math.pow((double) (f + g + h + n) * 0.25, 0.45454545454545453))); + return (int) ((double) o * 255.0); } private static int getPixelA(int rgba) { @@ -137,10 +135,10 @@ private static int calculateAverage(NativeImage nativeImage) { final int[] values = new int[width * height]; int count = 0; - long srcPtr = ((NativeImageAccessor)(Object)nativeImage).getPixels(); + long srcPtr = ((NativeImageAccessor) (Object) nativeImage).getPixels(); - for(int i = 0; i < width; ++i) { - for(int j = 0; j < height; ++j) { + for (int i = 0; i < width; ++i) { + for (int j = 0; j < height; ++j) { // int value = nativeImage.getPixelRGBA(i, j); int value = MemoryUtil.memGetInt(srcPtr + (i + (long) j * width) * 4L); if (((value >> 24) & 0xFF) > 0) { @@ -159,7 +157,7 @@ private static int calculateAverage(NativeImage nativeImage) { sumB += (values[i] >> 16) & 0xFF; } - if(count == 0) + if (count == 0) return 0; sumR /= count; diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java b/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java deleted file mode 100644 index e807e35bf..000000000 --- a/src/main/java/net/vulkanmod/mixin/texture/update/MLightTexture.java +++ /dev/null @@ -1,210 +0,0 @@ -package net.vulkanmod.mixin.texture.update; - -import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.systems.RenderSystem; -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.renderer.texture.DynamicTexture; -import net.minecraft.util.Mth; -import net.minecraft.world.effect.MobEffectInstance; -import net.minecraft.world.effect.MobEffects; -import net.minecraft.world.entity.LivingEntity; -import net.vulkanmod.gl.VkGlTexture; -import net.vulkanmod.mixin.texture.image.NativeImageAccessor; -import net.vulkanmod.render.texture.ImageUploadHelper; -import net.vulkanmod.vulkan.queue.CommandPool; -import org.joml.Vector3f; -import org.lwjgl.system.MemoryStack; -import org.lwjgl.system.MemoryUtil; -import org.spongepowered.asm.mixin.*; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(LightTexture.class) -public class MLightTexture { - @Shadow @Final private Minecraft minecraft; - @Shadow @Final private GameRenderer renderer; - - @Shadow private boolean updateLightTexture; - @Shadow private float blockLightRedFlicker; - - @Shadow @Final private DynamicTexture lightTexture; - @Shadow @Final private NativeImage lightPixels; - - - private Vector3f[] tempVecs; - - @Inject(method = "", at = @At("RETURN")) - private void onInit(GameRenderer gameRenderer, Minecraft minecraft, CallbackInfo ci) { - this.tempVecs = new Vector3f[]{new Vector3f(), new Vector3f(), new Vector3f()}; - } - - /** - * @author - * @reason - */ - @Overwrite - public void turnOnLightLayer() { - RenderSystem.setShaderTexture(2, this.lightTexture.getId()); - } - - @SuppressWarnings("UnreachableCode") - @Inject(method = "updateLightTexture", at = @At("HEAD"), cancellable = true) - public void updateLightTexture(float partialTicks, CallbackInfo ci) { - if (this.updateLightTexture) { - this.updateLightTexture = false; - - this.minecraft.getProfiler().push("lightTex"); - - // TODO: Other mods might be changing lightmap behaviour, we can't be aware of that here - - ClientLevel clientLevel = this.minecraft.level; - if (clientLevel != null) { - float skyDarken = clientLevel.getSkyDarken(1.0F); - float skyFlashTime; - if (clientLevel.getSkyFlashTime() > 0) { - skyFlashTime = 1.0F; - } else { - skyFlashTime = skyDarken * 0.95F + 0.05F; - } - - float darknessEffectScale = this.minecraft.options.darknessEffectScale().get().floatValue(); - float darknessGamma = this.getDarknessGamma(partialTicks) * darknessEffectScale; - float darknessScale = this.calculateDarknessScale(this.minecraft.player, darknessGamma, partialTicks) * darknessEffectScale; - float waterVision = this.minecraft.player.getWaterVision(); - float nightVisionFactor; - if (this.minecraft.player.hasEffect(MobEffects.NIGHT_VISION)) { - nightVisionFactor = GameRenderer.getNightVisionScale(this.minecraft.player, partialTicks); - } else if (waterVision > 0.0F && this.minecraft.player.hasEffect(MobEffects.CONDUIT_POWER)) { - nightVisionFactor = waterVision; - } else { - nightVisionFactor = 0.0F; - } - -// Vector3f skyLightColor = new Vector3f(skyDarken, skyDarken, 1.0F).lerp(new Vector3f(1.0F, 1.0F, 1.0F), 0.35F); - skyDarken = lerp(skyDarken, 1.0f, 0.35f); - Vector3f skyLightColor = this.tempVecs[0].set(skyDarken, skyDarken, 1.0F); - float redFlicker = this.blockLightRedFlicker + 1.5F; - Vector3f lightColor = this.tempVecs[1]; - - float gamma = this.minecraft.options.gamma().get().floatValue(); - float darkenWorldAmount = this.renderer.getDarkenWorldAmount(partialTicks); - boolean forceBrightLightmap = clientLevel.effects().forceBrightLightmap(); - float ambientLight = clientLevel.dimensionType().ambientLight(); - - long ptr = ((NativeImageAccessor)(Object)this.lightPixels).getPixels(); - int width = this.lightPixels.getWidth(); - - Vector3f tVec3f = this.tempVecs[2]; - - for(int y = 0; y < 16; ++y) { - float brY = getBrightness(ambientLight, y) * skyFlashTime; - - for(int x = 0; x < 16; ++x) { - float brX = getBrightness(ambientLight, x) * redFlicker; - float t = brX * ((brX * 0.6F + 0.4F) * 0.6F + 0.4F); - float u = brX * (brX * brX * 0.6F + 0.4F); - lightColor.set(brX, t, u); - - if (forceBrightLightmap) { - lightColor.lerp(tVec3f.set(0.99F, 1.12F, 1.0F), 0.25F); - clampColor(lightColor); - } else { - tVec3f.set(skyLightColor).mul(brY); - lightColor.add(tVec3f); - - tVec3f.set(0.75F, 0.75F, 0.75F); - lightColor.lerp(tVec3f, 0.04F); - - if (darkenWorldAmount > 0.0F) { - tVec3f.set(lightColor).mul(0.7F, 0.6F, 0.6F); - lightColor.lerp(tVec3f, darkenWorldAmount); - } - } - - if (nightVisionFactor > 0.0F) { - // scale up uniformly until 1.0 is hit by one of the colors - float maxComponent = Math.max(lightColor.x(), Math.max(lightColor.y(), lightColor.z())); - if (maxComponent < 1.0F) { - float brightColor = 1.0F / maxComponent; - tVec3f.set(lightColor).mul(brightColor); - lightColor.lerp(tVec3f, nightVisionFactor); - } - } - - if (!forceBrightLightmap) { - lightColor.add(-darknessScale, -darknessScale, -darknessScale); - clampColor(lightColor); - } - - tVec3f.set(this.notGamma(lightColor.x), this.notGamma(lightColor.y), this.notGamma(lightColor.z)); - lightColor.lerp(tVec3f, Math.max(0.0F, gamma - darknessGamma)); - - lightColor.lerp(tVec3f.set(0.75F, 0.75F, 0.75F), 0.04F); - clampColor(lightColor); - - lightColor.mul(255.0F); - int r = (int)lightColor.x(); - int g = (int)lightColor.y(); - int b = (int)lightColor.z(); - - MemoryUtil.memPutInt(ptr + (((long) y * width + x) * 4L), 0xFF000000 | b << 16 | g << 8 | r); - } - } - - CommandPool.CommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer(); - this.lightTexture.upload(); - - try (MemoryStack stack = MemoryStack.stackPush()) { - VkGlTexture.getTexture(this.lightTexture.getId()).getVulkanImage().readOnlyLayout(stack, commandBuffer.getHandle()); - } - - ImageUploadHelper.INSTANCE.submitCommands(); - - this.minecraft.getProfiler().pop(); - } - } - - ci.cancel(); - } - - @Unique - private float getDarknessGamma(float f) { - MobEffectInstance mobEffectInstance = this.minecraft.player.getEffect(MobEffects.DARKNESS); - return mobEffectInstance != null ? mobEffectInstance.getBlendFactor(this.minecraft.player, f) : 0.0F; - } - - @Unique - private float calculateDarknessScale(LivingEntity livingEntity, float f, float g) { - float h = 0.45F * f; - return Math.max(0.0F, Mth.cos(((float)livingEntity.tickCount - g) * (float) Math.PI * 0.025F) * h); - } - - @Unique - private static float lerp(float a, float x, float t) { - return (x - a) * t + a; - } - - @Unique - private static void clampColor(Vector3f vector3f) { - vector3f.set(Mth.clamp(vector3f.x, 0.0F, 1.0F), Mth.clamp(vector3f.y, 0.0F, 1.0F), Mth.clamp(vector3f.z, 0.0F, 1.0F)); - } - - @Unique - private float notGamma(float f) { - float g = 1.0F - f; - g = g * g; - return 1.0F - g * g; - } - - @Unique - private static float getBrightness(float ambientLight, int i) { - float f = (float)i / 15.0F; - float g = f / (4.0F - 3.0F * f); - return Mth.lerp(ambientLight, g, 1.0F); - } - -} diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java b/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java index ea6603d66..15dc332d1 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java +++ b/src/main/java/net/vulkanmod/mixin/texture/update/MSpriteContents.java @@ -13,9 +13,13 @@ @Mixin(SpriteContents.Ticker.class) public class MSpriteContents { - @Shadow int subFrame; - @Shadow int frame; - @Shadow @Final SpriteContents.AnimatedTexture animationInfo; + @Shadow + int subFrame; + @Shadow + int frame; + @Shadow + @Final + SpriteContents.AnimatedTexture animationInfo; @Inject(method = "tickAndUpload", at = @At("HEAD"), cancellable = true) private void checkUpload(int i, int j, CallbackInfo ci) { @@ -29,8 +33,7 @@ private void checkUpload(int i, int j, CallbackInfo ci) { } ci.cancel(); - } - else { + } else { SpriteUpdateUtil.addTransitionedLayout(VTextureSelector.getBoundTexture()); } } diff --git a/src/main/java/net/vulkanmod/mixin/texture/update/MTextureManager.java b/src/main/java/net/vulkanmod/mixin/texture/update/MTextureManager.java index 551f797ee..6175842ff 100644 --- a/src/main/java/net/vulkanmod/mixin/texture/update/MTextureManager.java +++ b/src/main/java/net/vulkanmod/mixin/texture/update/MTextureManager.java @@ -14,7 +14,9 @@ @Mixin(TextureManager.class) public abstract class MTextureManager { - @Shadow @Final private Set tickableTextures; + @Shadow + @Final + private Set tickableTextures; /** * @author diff --git a/src/main/java/net/vulkanmod/mixin/util/ScreenshotRecorderM.java b/src/main/java/net/vulkanmod/mixin/util/ScreenshotRecorderM.java deleted file mode 100644 index 703a79b77..000000000 --- a/src/main/java/net/vulkanmod/mixin/util/ScreenshotRecorderM.java +++ /dev/null @@ -1,32 +0,0 @@ -package net.vulkanmod.mixin.util; - -import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.platform.NativeImage; -import net.minecraft.client.Screenshot; -import net.vulkanmod.gl.VkGlTexture; -import net.vulkanmod.vulkan.Renderer; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -@Mixin(Screenshot.class) -public class ScreenshotRecorderM { - - /** - * @author - */ - @Overwrite - public static NativeImage takeScreenshot(RenderTarget target) { - int width = target.width; - int height = target.height; - - NativeImage nativeimage = new NativeImage(width, height, false); - VkGlTexture.bindTexture(target.getColorTextureId()); - - // Need to submit and wait cmds if screenshot was requested - // before the end of the frame - Renderer.getInstance().flushCmds(); - - nativeimage.downloadTexture(0, true); - return nativeimage; - } -} diff --git a/src/main/java/net/vulkanmod/mixin/vertex/SpriteCoordinateExpanderM.java b/src/main/java/net/vulkanmod/mixin/vertex/SpriteCoordinateExpanderM.java index c27452a11..5ff63fd3c 100644 --- a/src/main/java/net/vulkanmod/mixin/vertex/SpriteCoordinateExpanderM.java +++ b/src/main/java/net/vulkanmod/mixin/vertex/SpriteCoordinateExpanderM.java @@ -15,7 +15,9 @@ //TODO move @Mixin(SpriteCoordinateExpander.class) public class SpriteCoordinateExpanderM implements ExtendedVertexBuilder { - @Shadow @Final private TextureAtlasSprite sprite; + @Shadow + @Final + private TextureAtlasSprite sprite; @Unique private ExtendedVertexBuilder extDelegate; diff --git a/src/main/java/net/vulkanmod/mixin/vertex/VertexMultiConsumersM.java b/src/main/java/net/vulkanmod/mixin/vertex/VertexMultiConsumersM.java index 842c44fd2..ac437d9b4 100644 --- a/src/main/java/net/vulkanmod/mixin/vertex/VertexMultiConsumersM.java +++ b/src/main/java/net/vulkanmod/mixin/vertex/VertexMultiConsumersM.java @@ -22,8 +22,12 @@ public class VertexMultiConsumersM { @Mixin(targets = "com/mojang/blaze3d/vertex/VertexMultiConsumer$Double") public static class DoubleM implements ExtendedVertexBuilder { - @Shadow @Final private VertexConsumer first; - @Shadow @Final private VertexConsumer second; + @Shadow + @Final + private VertexConsumer first; + @Shadow + @Final + private VertexConsumer second; @Unique private ExtendedVertexBuilder firstExt; @@ -58,7 +62,9 @@ public void vertex(float x, float y, float z, int packedColor, float u, float v, @Mixin(targets = "com/mojang/blaze3d/vertex/VertexMultiConsumer$Multiple") public static class MultipleM implements ExtendedVertexBuilder { - @Shadow @Final private VertexConsumer[] delegates; + @Shadow + @Final + private VertexConsumer[] delegates; @Unique private boolean canUseFastVertex = false; @@ -92,10 +98,18 @@ public void vertex(float x, float y, float z, int packedColor, float u, float v, @Mixin(SheetedDecalTextureGenerator.class) public static abstract class SheetDecalM implements ExtendedVertexBuilder { - @Shadow @Final private VertexConsumer delegate; - @Shadow @Final private Matrix3f normalInversePose; - @Shadow @Final private Matrix4f cameraInversePose; - @Shadow @Final private float textureScale; + @Shadow + @Final + private VertexConsumer delegate; + @Shadow + @Final + private Matrix3f normalInversePose; + @Shadow + @Final + private Matrix4f cameraInversePose; + @Shadow + @Final + private float textureScale; @Unique private boolean canUseFastVertex = false; @@ -120,10 +134,10 @@ public void vertex(float x, float y, float z, int packedColor, float u, float v, float nz = I32_SNorm.unpackZ(packedNormal); normal.set(nx, ny, nz); - position.set(x, y , z, 1.0f); + position.set(x, y, z, 1.0f); this.normalInversePose.transform(normal); - Direction direction = Direction.getNearest(normal.x(), normal.y(), normal.z()); + Direction direction = Direction.getApproximateNearest(normal.x(), normal.y(), normal.z()); this.cameraInversePose.transform(position); position.rotateY(3.1415927F); position.rotateX(-1.5707964F); diff --git a/src/main/java/net/vulkanmod/mixin/voxel/VoxelShapeMixin.java b/src/main/java/net/vulkanmod/mixin/voxel/VoxelShapeMixin.java index 5331d81c7..a749071a3 100644 --- a/src/main/java/net/vulkanmod/mixin/voxel/VoxelShapeMixin.java +++ b/src/main/java/net/vulkanmod/mixin/voxel/VoxelShapeMixin.java @@ -1,6 +1,8 @@ package net.vulkanmod.mixin.voxel; -import net.minecraft.world.phys.shapes.*; +import net.minecraft.world.phys.shapes.CubeVoxelShape; +import net.minecraft.world.phys.shapes.DiscreteVoxelShape; +import net.minecraft.world.phys.shapes.VoxelShape; import net.vulkanmod.interfaces.VoxelShapeExtended; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -11,7 +13,9 @@ @Mixin(VoxelShape.class) public class VoxelShapeMixin implements VoxelShapeExtended { - @Shadow @Final protected DiscreteVoxelShape shape; + @Shadow + @Final + protected DiscreteVoxelShape shape; int co; @@ -22,8 +26,8 @@ private void initCornerOcclusion(DiscreteVoxelShape discreteVoxelShape, Callback // TODO: lithium subclasses // lithium is using its own classes for simple cube shapes - VoxelShape shape = (VoxelShape)((Object)this); - if(!(shape instanceof CubeVoxelShape) || disShape == null) { + VoxelShape shape = (VoxelShape) ((Object) this); + if (!(shape instanceof CubeVoxelShape) || disShape == null) { this.co = 0; return; } diff --git a/src/main/java/net/vulkanmod/mixin/wayland/InputConstantsM.java b/src/main/java/net/vulkanmod/mixin/wayland/InputConstantsM.java index 7c4ee506c..f86c7c34a 100644 --- a/src/main/java/net/vulkanmod/mixin/wayland/InputConstantsM.java +++ b/src/main/java/net/vulkanmod/mixin/wayland/InputConstantsM.java @@ -2,7 +2,7 @@ import com.mojang.blaze3d.platform.InputConstants; import net.vulkanmod.config.Platform; -import org.lwjgl.glfw.*; +import org.lwjgl.glfw.GLFW; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; diff --git a/src/main/java/net/vulkanmod/mixin/wayland/MinecraftMixin.java b/src/main/java/net/vulkanmod/mixin/wayland/MinecraftMixin.java index a80b32c0b..c6cd0f544 100644 --- a/src/main/java/net/vulkanmod/mixin/wayland/MinecraftMixin.java +++ b/src/main/java/net/vulkanmod/mixin/wayland/MinecraftMixin.java @@ -8,7 +8,6 @@ import net.minecraft.server.packs.PackResources; import net.minecraft.server.packs.VanillaPackResources; import net.vulkanmod.config.Platform; -import net.vulkanmod.config.video.VideoModeManager; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -20,20 +19,24 @@ @Mixin(Minecraft.class) public class MinecraftMixin { - @Shadow @Final private Window window; - @Shadow @Final public Options options; - - @Shadow @Final private VanillaPackResources vanillaPackResources; + @Shadow + @Final + public Options options; + @Shadow + @Final + private Window window; + @Shadow + @Final + private VanillaPackResources vanillaPackResources; /** * @author * @reason Only KWin supports setting the Icon on Wayland AFAIK */ - @Redirect(method="", at=@At(value="INVOKE", target="Lcom/mojang/blaze3d/platform/Window;setIcon(Lnet/minecraft/server/packs/PackResources;Lcom/mojang/blaze3d/platform/IconSet;)V")) + @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/Window;setIcon(Lnet/minecraft/server/packs/PackResources;Lcom/mojang/blaze3d/platform/IconSet;)V")) private void bypassWaylandIcon(Window instance, PackResources packResources, IconSet iconSet) throws IOException { - if(!Platform.isWayLand()) - { - this.window.setIcon(this.vanillaPackResources, SharedConstants.getCurrentVersion().isStable() ? IconSet.RELEASE : IconSet.SNAPSHOT); + if (!Platform.isWayLand()) { + this.window.setIcon(this.vanillaPackResources, SharedConstants.getCurrentVersion().stable() ? IconSet.RELEASE : IconSet.SNAPSHOT); } } } diff --git a/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java b/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java index 5f4c71ce8..e5e6f7299 100644 --- a/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java +++ b/src/main/java/net/vulkanmod/mixin/window/WindowMixin.java @@ -1,19 +1,23 @@ package net.vulkanmod.mixin.window; -import com.mojang.blaze3d.platform.*; +import com.mojang.blaze3d.TracyFrameCapture; +import com.mojang.blaze3d.platform.DisplayData; +import com.mojang.blaze3d.platform.ScreenManager; +import com.mojang.blaze3d.platform.Window; +import com.mojang.blaze3d.platform.WindowEventHandler; import com.mojang.blaze3d.systems.RenderSystem; import net.vulkanmod.Initializer; import net.vulkanmod.config.Config; import net.vulkanmod.config.Platform; -import net.vulkanmod.config.video.VideoModeManager; import net.vulkanmod.config.option.Options; +import net.vulkanmod.config.video.VideoModeManager; import net.vulkanmod.config.video.VideoModeSet; import net.vulkanmod.config.video.WindowMode; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.Vulkan; +import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; -import org.lwjgl.opengl.GLCapabilities; import org.slf4j.Logger; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -21,60 +25,54 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import static org.lwjgl.glfw.GLFW.*; @Mixin(Window.class) public abstract class WindowMixin { - @Final @Shadow private long window; - - @Shadow private boolean vsync; - - @Shadow protected abstract void updateFullscreen(boolean bl); - - @Shadow private boolean fullscreen; - - @Shadow @Final private static Logger LOGGER; - - @Shadow private int windowedX; - @Shadow private int windowedY; - @Shadow private int windowedWidth; - @Shadow private int windowedHeight; - @Shadow private int x; - @Shadow private int y; - @Shadow private int width; - @Shadow private int height; - - @Shadow private int framebufferWidth; - @Shadow private int framebufferHeight; - - @Shadow public abstract int getWidth(); - - @Shadow public abstract int getHeight(); - - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lorg/lwjgl/glfw/GLFW;glfwWindowHint(II)V")) - private void redirect(int hint, int value) { } + @Shadow + @Final + private static Logger LOGGER; + @Final + @Shadow + private long handle; + @Shadow + private boolean vsync; + @Shadow + private boolean fullscreen; + @Shadow + private int windowedX; + @Shadow + private int windowedY; + @Shadow + private int windowedWidth; + @Shadow + private int windowedHeight; + @Shadow + private int x; + @Shadow + private int y; + @Shadow + private int width; + @Shadow + private int height; + @Shadow + private int framebufferWidth; + @Shadow + private int framebufferHeight; + private boolean wasOnFullscreen = false; - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lorg/lwjgl/glfw/GLFW;glfwMakeContextCurrent(J)V")) - private void redirect2(long window) { } + @Shadow + protected abstract void updateFullscreen(boolean bl, @Nullable TracyFrameCapture tracyFrameCapture); - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL;createCapabilities()Lorg/lwjgl/opengl/GLCapabilities;")) - private GLCapabilities redirect2() { - return null; - } - - // Vulkan device not initialized yet - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;maxSupportedTextureSize()I")) - private int redirect3() { - return 0; - } + @Shadow + public abstract int getWidth(); - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lorg/lwjgl/glfw/GLFW;glfwSetWindowSizeLimits(JIIII)V")) - private void redirect4(long window, int minwidth, int minheight, int maxwidth, int maxheight) { } + @Shadow + public abstract int getHeight(); - @Inject(method = "", at = @At(value = "INVOKE", target = "Lorg/lwjgl/glfw/GLFW;glfwCreateWindow(IILjava/lang/CharSequence;JJ)J")) + @Inject(method = "", at = @At(value = "INVOKE", target = "Lorg/lwjgl/glfw/GLFW;glfwCreateWindow(IILjava/lang/CharSequence;JJ)J"), remap = false) private void vulkanHint(WindowEventHandler windowEventHandler, ScreenManager screenManager, DisplayData displayData, String string, String string2, CallbackInfo ci) { GLFW.glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); @@ -85,7 +83,7 @@ private void vulkanHint(WindowEventHandler windowEventHandler, ScreenManager scr @Inject(method = "", at = @At(value = "RETURN")) private void getHandle(WindowEventHandler windowEventHandler, ScreenManager screenManager, DisplayData displayData, String string, String string2, CallbackInfo ci) { - VRenderSystem.setWindow(this.window); + VRenderSystem.setWindow(this.handle); } /** @@ -110,17 +108,15 @@ public void toggleFullScreen() { * @author */ @Overwrite - public void updateDisplay() { - RenderSystem.flipFrame(this.window); + public void updateDisplay(@Nullable TracyFrameCapture tracyFrameCapture) { + RenderSystem.flipFrame((Window) (Object) this, tracyFrameCapture); if (Options.fullscreenDirty) { Options.fullscreenDirty = false; - this.updateFullscreen(this.vsync); + this.updateFullscreen(this.vsync, tracyFrameCapture); } } - private boolean wasOnFullscreen = false; - /** * @author */ @@ -138,12 +134,11 @@ private void setMode() { if (set != null) { supported = set.hasRefreshRate(videoMode.refreshRate); - } - else { + } else { supported = false; } - if(!supported) { + if (!supported) { LOGGER.error("Resolution not supported, using first available as fallback"); videoMode = VideoModeManager.getFirstAvailable().getVideoMode(); } @@ -159,12 +154,11 @@ private void setMode() { this.y = 0; this.width = videoMode.width; this.height = videoMode.height; - GLFW.glfwSetWindowMonitor(this.window, monitor, this.x, this.y, this.width, this.height, videoMode.refreshRate); + GLFW.glfwSetWindowMonitor(this.handle, monitor, this.x, this.y, this.width, this.height, videoMode.refreshRate); this.wasOnFullscreen = true; } - } - else if (config.windowMode == WindowMode.WINDOWED_FULLSCREEN.mode) { + } else if (config.windowMode == WindowMode.WINDOWED_FULLSCREEN.mode) { VideoModeSet.VideoMode videoMode = VideoModeManager.getOsVideoMode(); if (!this.wasOnFullscreen) { @@ -177,8 +171,8 @@ else if (config.windowMode == WindowMode.WINDOWED_FULLSCREEN.mode) { int width = videoMode.width; int height = videoMode.height; - GLFW.glfwSetWindowAttrib(this.window, GLFW_DECORATED, GLFW_FALSE); - GLFW.glfwSetWindowMonitor(this.window, 0L, 0, 0, width, height, -1); + GLFW.glfwSetWindowAttrib(this.handle, GLFW_DECORATED, GLFW_FALSE); + GLFW.glfwSetWindowMonitor(this.handle, 0L, 0, 0, width, height, -1); this.width = width; this.height = height; @@ -189,8 +183,8 @@ else if (config.windowMode == WindowMode.WINDOWED_FULLSCREEN.mode) { this.width = this.windowedWidth; this.height = this.windowedHeight; - GLFW.glfwSetWindowMonitor(this.window, 0L, this.x, this.y, this.width, this.height, -1); - GLFW.glfwSetWindowAttrib(this.window, GLFW_DECORATED, GLFW_TRUE); + GLFW.glfwSetWindowMonitor(this.handle, 0L, this.x, this.y, this.width, this.height, -1); + GLFW.glfwSetWindowAttrib(this.handle, GLFW_DECORATED, GLFW_TRUE); this.wasOnFullscreen = false; } @@ -202,11 +196,11 @@ else if (config.windowMode == WindowMode.WINDOWED_FULLSCREEN.mode) { */ @Overwrite private void onFramebufferResize(long window, int width, int height) { - if (window == this.window) { + if (window == this.handle) { int prevWidth = this.getWidth(); int prevHeight = this.getHeight(); - if(width > 0 && height > 0) { + if (width > 0 && height > 0) { this.framebufferWidth = width; this.framebufferHeight = height; // if (this.framebufferWidth != prevWidth || this.framebufferHeight != prevHeight) { @@ -228,7 +222,7 @@ private void onResize(long window, int width, int height) { this.width = width; this.height = height; - if(width > 0 && height > 0) + if (width > 0 && height > 0) Renderer.scheduleSwapChainUpdate(); } diff --git a/src/main/java/net/vulkanmod/render/PipelineManager.java b/src/main/java/net/vulkanmod/render/PipelineManager.java index 97bca6f33..a0e02c54f 100644 --- a/src/main/java/net/vulkanmod/render/PipelineManager.java +++ b/src/main/java/net/vulkanmod/render/PipelineManager.java @@ -1,31 +1,39 @@ package net.vulkanmod.render; import com.google.gson.JsonObject; +import com.mojang.blaze3d.pipeline.RenderPipeline; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.RenderType; +import net.minecraft.resources.ResourceLocation; import net.vulkanmod.render.chunk.build.thread.ThreadBuilderPack; import net.vulkanmod.render.shader.ShaderLoadUtil; import net.vulkanmod.render.vertex.CustomVertexFormat; import net.vulkanmod.render.vertex.TerrainRenderType; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.shader.Pipeline; +import net.vulkanmod.vulkan.shader.RayTracingPipeline; +import net.vulkanmod.vulkan.shader.SPIRVUtils; +import java.util.HashMap; +import java.util.Map; import java.util.function.Function; public abstract class PipelineManager { + private static final Map dynamicPipelines = new HashMap<>(); public static VertexFormat terrainVertexFormat; - - public static void setTerrainVertexFormat(VertexFormat format) { - terrainVertexFormat = format; - } - static GraphicsPipeline terrainShader, terrainShaderEarlyZ, fastBlitPipeline, cloudsPipeline; + static RayTracingPipeline rayTracingPipeline; + private static Function shaderGetter; + public static void setTerrainVertexFormat(VertexFormat format) { + terrainVertexFormat = format; + } + public static void init() { setTerrainVertexFormat(CustomVertexFormat.COMPRESSED_TERRAIN); createBasicPipelines(); @@ -43,12 +51,17 @@ private static void createBasicPipelines() { terrainShader = createPipeline("terrain", terrainVertexFormat); fastBlitPipeline = createPipeline("blit", CustomVertexFormat.NONE); cloudsPipeline = createPipeline("clouds", DefaultVertexFormat.POSITION_COLOR); + rayTracingPipeline = createRayTracingPipeline("raytracing"); } private static GraphicsPipeline createPipeline(String configName, VertexFormat vertexFormat) { Pipeline.Builder pipelineBuilder = new Pipeline.Builder(vertexFormat, configName); JsonObject config = ShaderLoadUtil.getJsonConfig("basic", configName); + if (config == null) { + return null; + } + pipelineBuilder.parseBindings(config); ShaderLoadUtil.loadShaders(pipelineBuilder, config, configName, "basic"); @@ -56,6 +69,23 @@ private static GraphicsPipeline createPipeline(String configName, VertexFormat v return pipelineBuilder.createGraphicsPipeline(); } + private static RayTracingPipeline createRayTracingPipeline(String configName) { + RayTracingPipeline.Builder pipelineBuilder = new RayTracingPipeline.Builder(configName); + + JsonObject config = ShaderLoadUtil.getJsonConfig("raytracing", configName); + if (config == null) { + return null; + } + + pipelineBuilder.parseBindings(config); + + ShaderLoadUtil.loadShader(pipelineBuilder, configName, "raytracing", SPIRVUtils.ShaderKind.RAYGEN_SHADER); + ShaderLoadUtil.loadShader(pipelineBuilder, configName, "raytracing", SPIRVUtils.ShaderKind.MISS_SHADER); + ShaderLoadUtil.loadShader(pipelineBuilder, configName, "raytracing", SPIRVUtils.ShaderKind.CLOSEST_HIT_SHADER); + + return pipelineBuilder.createRayTracingPipeline(); + } + public static GraphicsPipeline getTerrainShader(TerrainRenderType renderType) { return shaderGetter.apply(renderType); } @@ -80,10 +110,41 @@ public static GraphicsPipeline getCloudsPipeline() { return cloudsPipeline; } + public static RayTracingPipeline getRayTracingPipeline() { + return rayTracingPipeline; + } + public static void destroyPipelines() { terrainShaderEarlyZ.cleanUp(); terrainShader.cleanUp(); fastBlitPipeline.cleanUp(); cloudsPipeline.cleanUp(); + if (rayTracingPipeline != null) { + rayTracingPipeline.cleanUp(); + } + dynamicPipelines.values().forEach(GraphicsPipeline::cleanUp); + dynamicPipelines.clear(); + } + + public static GraphicsPipeline getPipeline(RenderPipeline pipeline, VertexFormat fallbackFormat) { + ResourceLocation location = pipeline.getLocation(); + GraphicsPipeline cached = dynamicPipelines.get(location); + if (cached != null) { + return cached; + } + + String configName = location.getPath(); + VertexFormat vertexFormat = pipeline.getVertexFormat(); + if (vertexFormat == null) { + vertexFormat = fallbackFormat != null ? fallbackFormat : terrainVertexFormat; + } + + GraphicsPipeline graphicsPipeline = createPipeline(configName, vertexFormat); + if (graphicsPipeline == null) { + return terrainShader; + } + + dynamicPipelines.put(location, graphicsPipeline); + return graphicsPipeline; } } diff --git a/src/main/java/net/vulkanmod/render/VBO.java b/src/main/java/net/vulkanmod/render/VBO.java index 48f10decb..17bb95b31 100644 --- a/src/main/java/net/vulkanmod/render/VBO.java +++ b/src/main/java/net/vulkanmod/render/VBO.java @@ -5,19 +5,20 @@ import com.mojang.blaze3d.vertex.VertexFormat; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.ShaderInstance; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; -import net.vulkanmod.vulkan.memory.*; +import net.vulkanmod.vulkan.memory.MemoryType; +import net.vulkanmod.vulkan.memory.MemoryTypes; import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; import net.vulkanmod.vulkan.memory.buffer.VertexBuffer; import net.vulkanmod.vulkan.memory.buffer.index.AutoIndexBuffer; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.texture.VTextureSelector; import org.joml.Matrix4f; +import org.lwjgl.opengl.GL11; import java.nio.ByteBuffer; +import java.nio.FloatBuffer; @Environment(EnvType.CLIENT) public class VBO { @@ -30,8 +31,29 @@ public class VBO { private int indexCount; private int vertexCount; - public VBO(com.mojang.blaze3d.vertex.VertexBuffer.Usage usage) { - this.memoryType = usage == com.mojang.blaze3d.vertex.VertexBuffer.Usage.STATIC ? MemoryTypes.GPU_MEM : MemoryTypes.HOST_MEM; + public VBO() { + this(MemoryTypes.GPU_MEM); + } + + public VBO(MemoryType memoryType) { + this.memoryType = memoryType; + } + + private static Matrix4f snapshotMatrix(ByteBuffer buffer) { + FloatBuffer floatBuffer = buffer.asFloatBuffer().duplicate(); + floatBuffer.rewind(); + return new Matrix4f(floatBuffer); + } + + private static int toGlMode(VertexFormat.Mode mode) { + return switch (mode) { + case LINES, DEBUG_LINES -> GL11.GL_LINES; + case LINE_STRIP, DEBUG_LINE_STRIP -> GL11.GL_LINE_STRIP; + case TRIANGLES -> GL11.GL_TRIANGLES; + case TRIANGLE_STRIP -> GL11.GL_TRIANGLE_STRIP; + case TRIANGLE_FAN -> GL11.GL_TRIANGLE_FAN; + case QUADS -> GL11.GL_QUADS; + }; } public void upload(MeshData meshData) { @@ -96,8 +118,7 @@ public void uploadIndexBuffer(ByteBuffer data) { } this.autoIndexed = true; - } - else { + } else { if (this.indexBuffer != null && !this.autoIndexed) { this.indexBuffer.scheduleFree(); } @@ -107,36 +128,15 @@ public void uploadIndexBuffer(ByteBuffer data) { } } - public void drawWithShader(Matrix4f modelView, Matrix4f projection, ShaderInstance shaderInstance) { - if (this.indexCount != 0) { - RenderSystem.assertOnRenderThread(); - - RenderSystem.setShader(() -> shaderInstance); - - VRenderSystem.applyMVP(modelView, projection); - VRenderSystem.setPrimitiveTopologyGL(this.mode.asGLMode); - - shaderInstance.setDefaultUniforms(VertexFormat.Mode.QUADS, modelView, projection, Minecraft.getInstance().getWindow()); - shaderInstance.apply(); - - if (this.indexBuffer != null) { - Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); - } - else { - Renderer.getDrawer().draw(this.vertexBuffer, this.vertexCount); - } - - // Reset MVP to previous state - VRenderSystem.applyMVP(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix()); - } - } - public void drawWithShader(Matrix4f modelView, Matrix4f projection, GraphicsPipeline pipeline) { if (this.indexCount != 0) { RenderSystem.assertOnRenderThread(); + Matrix4f previousModelView = snapshotMatrix(VRenderSystem.getModelViewMatrix().buffer); + Matrix4f previousProjection = snapshotMatrix(VRenderSystem.getProjectionMatrix().buffer); + VRenderSystem.applyMVP(modelView, projection); - VRenderSystem.setPrimitiveTopologyGL(this.mode.asGLMode); + VRenderSystem.setPrimitiveTopologyGL(toGlMode(this.mode)); Renderer renderer = Renderer.getInstance(); renderer.bindGraphicsPipeline(pipeline); @@ -145,13 +145,11 @@ public void drawWithShader(Matrix4f modelView, Matrix4f projection, GraphicsPipe if (this.indexBuffer != null) { Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); - } - else { + } else { Renderer.getDrawer().draw(this.vertexBuffer, this.vertexCount); } - // Reset MVP to previous state - VRenderSystem.applyMVP(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix()); + VRenderSystem.applyMVP(previousModelView, previousProjection); } } @@ -159,8 +157,7 @@ public void draw() { if (this.indexCount != 0) { if (this.indexBuffer != null) { Renderer.getDrawer().drawIndexed(this.vertexBuffer, this.indexBuffer, this.indexCount); - } - else { + } else { Renderer.getDrawer().draw(this.vertexBuffer, this.vertexCount); } } diff --git a/src/main/java/net/vulkanmod/render/chunk/ChunkArea.java b/src/main/java/net/vulkanmod/render/chunk/ChunkArea.java index 85400a8f1..4c30c3394 100644 --- a/src/main/java/net/vulkanmod/render/chunk/ChunkArea.java +++ b/src/main/java/net/vulkanmod/render/chunk/ChunkArea.java @@ -11,15 +11,13 @@ public class ChunkArea { public final int index; + //Help JIT optimisations by hardcoding the queue size to the max possible ChunkArea limit + public final StaticQueue sectionQueue = new StaticQueue<>(512); final DrawBuffers drawBuffers; final Vector3i position; final byte[] frustumBuffer = new byte[64]; - int sectionsContained = 0; - //Help JIT optimisations by hardcoding the queue size to the max possible ChunkArea limit - public final StaticQueue sectionQueue = new StaticQueue<>(512); - public ChunkArea(int i, Vector3i origin, int minHeight) { this.index = i; this.position = origin; @@ -29,17 +27,17 @@ public ChunkArea(int i, Vector3i origin, int minHeight) { public void updateFrustum(VFrustum frustum) { //TODO: maybe move to an aux class int frustumResult = frustum.cubeInFrustum(this.position.x(), this.position.y(), this.position.z(), - this.position.x() + (8 << 4) , this.position.y() + (8 << 4), this.position.z() + (8 << 4)); + this.position.x() + (8 << 4), this.position.y() + (8 << 4), this.position.z() + (8 << 4)); //Inner cubes if (frustumResult == FrustumIntersection.INTERSECT) { int width = 8 << 4; int l = width >> 1; - for(int x1 = 0; x1 < 2; x1++) { + for (int x1 = 0; x1 < 2; x1++) { float xMin = this.position.x() + (x1 * l); float xMax = xMin + l; - for(int y1 = 0; y1 < 2; y1++) { + for (int y1 = 0; y1 < 2; y1++) { float yMin = this.position.y() + (y1 * l); float yMax = yMin + l; for (int z1 = 0; z1 < 2; z1++) { @@ -47,7 +45,7 @@ public void updateFrustum(VFrustum frustum) { float zMax = zMin + l; frustumResult = frustum.cubeInFrustum(xMin, yMin, zMin, - xMax , yMax, zMax); + xMax, yMax, zMax); int beginIdx = (x1 << 5) + (y1 << 4) + (z1 << 3); if (frustumResult == FrustumIntersection.INTERSECT) { @@ -72,11 +70,10 @@ public void updateFrustum(VFrustum frustum) { } } - } - else { + } else { int end = beginIdx + 8; - for(int i = beginIdx; i < end; ++i) { + for (int i = beginIdx; i < end; ++i) { this.frustumBuffer[i] = (byte) frustumResult; } } diff --git a/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java b/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java index 4b79212b6..4fd9d32c6 100644 --- a/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java +++ b/src/main/java/net/vulkanmod/render/chunk/ChunkAreaManager.java @@ -14,26 +14,22 @@ public class ChunkAreaManager { public static final int AREA_SIZE = WIDTH * WIDTH * HEIGHT; - public static final int AREA_SH_XZ = Util.flooredLog(WIDTH); - public static final int AREA_SH_Y = Util.flooredLog(HEIGHT); - public static final int SEC_SH = 4; + public static final int AREA_SH_XZ = Util.flooredLog(WIDTH); public static final int BLOCK_TO_AREA_SH_XZ = AREA_SH_XZ + SEC_SH; + public static final int AREA_SH_Y = Util.flooredLog(HEIGHT); public static final int BLOCK_TO_AREA_SH_Y = AREA_SH_Y + SEC_SH; - public final int size; final int sectionGridWidth; final int xzSize; final int ySize; final int minHeight; final ChunkArea[] chunkAreasArr; - - int prevX; - int prevZ; - private final CircularIntList xList; private final CircularIntList zList; private final CircularIntList.RangeIterator xComplIterator; + int prevX; + int prevZ; public ChunkAreaManager(int width, int height, int minHeight) { this.minHeight = minHeight; @@ -246,7 +242,7 @@ public String[] getStats() { vbUsed /= div; ibSize /= div; ibUsed /= div; - frag /= div; + frag /= div; return new String[]{ String.format("Vertex Buffers: %d/%d MB", vbUsed, vbSize), diff --git a/src/main/java/net/vulkanmod/render/chunk/ChunkStatusMap.java b/src/main/java/net/vulkanmod/render/chunk/ChunkStatusMap.java index 56e2206d5..0a4b5da2b 100644 --- a/src/main/java/net/vulkanmod/render/chunk/ChunkStatusMap.java +++ b/src/main/java/net/vulkanmod/render/chunk/ChunkStatusMap.java @@ -11,11 +11,6 @@ public class ChunkStatusMap { public static final byte ALL_FLAGS = CHUNK_READY | NEIGHBOURS_READY; public static ChunkStatusMap INSTANCE; - - public static void createInstance(int renderDistance) { - INSTANCE = new ChunkStatusMap(renderDistance); - } - private final Long2ByteOpenHashMap map; public ChunkStatusMap(int renderDistance) { @@ -24,6 +19,10 @@ public ChunkStatusMap(int renderDistance) { map.defaultReturnValue((byte) 0); } + public static void createInstance(int renderDistance) { + INSTANCE = new ChunkStatusMap(renderDistance); + } + public void updateDistance(int renderDistance) { int diameter = renderDistance * 2 + 1; this.map.ensureCapacity(diameter * diameter); @@ -55,8 +54,7 @@ public void updateNeighbours(int x, int z) { for (int z1 = z - 1; z1 <= z + 1; ++z1) { if (checkNeighbours(x1, z1)) { map.put(ChunkPos.asLong(x1, z1), ALL_FLAGS); - } - else { + } else { long l = ChunkPos.asLong(x1, z1); byte current = map.get(l); diff --git a/src/main/java/net/vulkanmod/render/chunk/RenderSection.java b/src/main/java/net/vulkanmod/render/chunk/RenderSection.java index 7e4d79046..678981ce1 100644 --- a/src/main/java/net/vulkanmod/render/chunk/RenderSection.java +++ b/src/main/java/net/vulkanmod/render/chunk/RenderSection.java @@ -1,8 +1,6 @@ package net.vulkanmod.render.chunk; -import com.google.common.collect.Sets; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; -import net.minecraft.client.Minecraft; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.vulkanmod.render.chunk.buffer.AreaBuffer; @@ -10,11 +8,7 @@ import net.vulkanmod.render.chunk.buffer.DrawParametersBuffer; import net.vulkanmod.render.chunk.build.RenderRegion; import net.vulkanmod.render.chunk.build.RenderRegionBuilder; -import net.vulkanmod.render.chunk.build.task.TaskDispatcher; -import net.vulkanmod.render.chunk.build.task.BuildTask; -import net.vulkanmod.render.chunk.build.task.ChunkTask; -import net.vulkanmod.render.chunk.build.task.CompiledSection; -import net.vulkanmod.render.chunk.build.task.SortTransparencyTask; +import net.vulkanmod.render.chunk.build.task.*; import net.vulkanmod.render.chunk.cull.QuadFacing; import net.vulkanmod.render.chunk.graph.GraphDirections; import net.vulkanmod.render.chunk.util.Util; @@ -24,35 +18,29 @@ import java.util.Set; public class RenderSection { - private ChunkArea chunkArea; + private final CompileStatus compileStatus = new CompileStatus(); public byte frustumIndex; public short lastFrame = -1; - private short lastFrame2 = -1; public short inAreaIndex; - public byte adjDirs; public RenderSection adjDown, adjUp, adjNorth, adjSouth, adjWest, adjEast; - - private final CompileStatus compileStatus = new CompileStatus(); - - private boolean dirty = true; - private boolean playerChanged; - private boolean completelyEmpty = true; - private boolean containsBlockEntities = false; - public long visibility; - public int xOffset, yOffset, zOffset; - // Graph-info public byte mainDir; public byte directions; public byte sourceDirs; public byte steps; public byte directionChanges; + private ChunkArea chunkArea; + private short lastFrame2 = -1; + private boolean dirty = true; + private boolean playerChanged; + private boolean completelyEmpty = true; + private boolean containsBlockEntities = false; public RenderSection(int index, int x, int y, int z) { this.xOffset = x; @@ -274,6 +262,12 @@ public boolean isDirty() { return this.dirty; } + public void setDirty(boolean playerChanged) { + this.playerChanged = playerChanged || this.dirty && this.playerChanged; + this.dirty = true; + WorldRenderer.getInstance().scheduleGraphUpdate(); + } + public boolean isDirtyFromPlayer() { return this.dirty && this.playerChanged; } @@ -306,30 +300,26 @@ public void resetDrawParameters(TerrainRenderType renderType) { } } + public ChunkArea getChunkArea() { + return this.chunkArea; + } + public void setChunkArea(ChunkArea chunkArea) { this.chunkArea = chunkArea; this.frustumIndex = chunkArea.getFrustumIndex(xOffset, yOffset, zOffset); } - public ChunkArea getChunkArea() { - return this.chunkArea; - } - public CompiledSection getCompiledSection() { return compileStatus.compiledSection; } - public boolean isCompiled() { - return this.compileStatus.compiledSection != CompiledSection.UNCOMPILED; - } - - public void setVisibility(long visibility) { - this.visibility = visibility; + public void setCompiledSection(CompiledSection compiledSection) { + this.compileStatus.compiledSection = compiledSection; } - public void setCompletelyEmpty(boolean b) { - this.completelyEmpty = b; + public boolean isCompiled() { + return this.compileStatus.compiledSection != CompiledSection.UNCOMPILED; } public void setContainsBlockEntities(boolean b) { @@ -348,10 +338,18 @@ public long getVisibility() { return visibility; } + public void setVisibility(long visibility) { + this.visibility = visibility; + } + public boolean isCompletelyEmpty() { return this.completelyEmpty; } + public void setCompletelyEmpty(boolean b) { + this.completelyEmpty = b; + } + public boolean containsBlockEntities() { return this.containsBlockEntities; } @@ -360,15 +358,8 @@ public void updateGlobalBlockEntities(Collection fullSet) { Set sectionSet = compileStatus.globalBlockEntities; if (sectionSet.size() != fullSet.size() || !sectionSet.containsAll(fullSet)) { - Set toRemove = Sets.newHashSet(sectionSet); - Set toAdd = Sets.newHashSet(fullSet); - toAdd.removeAll(sectionSet); - toRemove.removeAll(fullSet); - sectionSet.clear(); sectionSet.addAll(fullSet); - - Minecraft.getInstance().levelRenderer.updateGlobalBlockEntities(toRemove, toAdd); } } @@ -395,16 +386,6 @@ private void resetDrawParameters() { } } - public void setDirty(boolean playerChanged) { - this.playerChanged = playerChanged || this.dirty && this.playerChanged; - this.dirty = true; - WorldRenderer.getInstance().scheduleGraphUpdate(); - } - - public void setCompiledSection(CompiledSection compiledSection) { - this.compileStatus.compiledSection = compiledSection; - } - public boolean setLastFrame(short i) { boolean alreadySet = i == this.lastFrame; if (!alreadySet) diff --git a/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java b/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java index b6d142b22..ca94a788f 100644 --- a/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java +++ b/src/main/java/net/vulkanmod/render/chunk/SectionGrid.java @@ -15,23 +15,21 @@ public class SectionGrid { protected final Level level; - protected int gridHeight; - protected int gridWidth; - public RenderSection[] sections; final ChunkAreaManager chunkAreaManager; - - private int prevSecX; - private int prevSecZ; - private final CircularIntList xList; private final CircularIntList zList; private final CircularIntList.RangeIterator xComplIterator; + public RenderSection[] sections; + protected int gridHeight; + protected int gridWidth; + private int prevSecX; + private int prevSecZ; public SectionGrid(Level level, int viewDistance) { this.level = level; this.setViewDistance(viewDistance); this.createChunks(); - this.chunkAreaManager = new ChunkAreaManager(this.gridWidth, this.gridHeight, this.level.getMinBuildHeight()); + this.chunkAreaManager = new ChunkAreaManager(this.gridWidth, this.gridHeight, this.level.getMinY()); this.prevSecX = Integer.MIN_VALUE; this.prevSecZ = Integer.MIN_VALUE; @@ -147,7 +145,7 @@ public void repositionCamera(double x, double z) { for (int yRel = 0; yRel < this.gridHeight; ++yRel) { moveSection(xRelativeIndex, yRel, zRelativeIndex, x1, z1, - xList, zList, xRangeIterator.getCurrentIndex(), zIterator.getCurrentIndex()); + xList, zList, xRangeIterator.getCurrentIndex(), zIterator.getCurrentIndex()); } } } @@ -166,7 +164,7 @@ public void repositionCamera(double x, double z) { for (int yRel = 0; yRel < this.gridHeight; ++yRel) { moveSection(xRelativeIndex, yRel, zRelativeIndex, x1, z1, - xList, zList, xComplIterator.getCurrentIndex(), zRangeIterator.getCurrentIndex()); + xList, zList, xComplIterator.getCurrentIndex(), zRangeIterator.getCurrentIndex()); } } } @@ -180,7 +178,7 @@ private void moveSection(int xRelativeIndex, int yRel, int zRelativeIndex, CircularIntList xList, CircularIntList zList, int xCurrentIdx, int zCurrentIdx) { - int y1 = this.level.getMinBuildHeight() + (yRel << 4); + int y1 = this.level.getMinY() + (yRel << 4); RenderSection renderSection = this.sections[this.getChunkIndex(xRelativeIndex, yRel, zRelativeIndex)]; this.unsetNeighbours(renderSection); @@ -188,7 +186,7 @@ private void moveSection(int xRelativeIndex, int yRel, int zRelativeIndex, renderSection.setOrigin(x1, y1, z1); this.setNeighbours(renderSection, xList, zList, xCurrentIdx, zCurrentIdx, - xRelativeIndex, yRel, zRelativeIndex); + xRelativeIndex, yRel, zRelativeIndex); ChunkArea oldArea = renderSection.getChunkArea(); @@ -281,7 +279,7 @@ private void setChunkArea(RenderSection section, int x, int y, int z) { public void setDirty(int sectionX, int sectionY, int sectionZ, boolean playerChanged) { int i = Math.floorMod(sectionX, this.gridWidth); - int j = Math.floorMod(sectionY - this.level.getMinSection(), this.gridHeight); + int j = Math.floorMod(sectionY - this.level.getMinSectionY(), this.gridHeight); int k = Math.floorMod(sectionZ, this.gridWidth); RenderSection renderSection = this.sections[this.getChunkIndex(i, j, k)]; renderSection.setDirty(playerChanged); @@ -294,7 +292,7 @@ public RenderSection getSectionAtBlockPos(BlockPos blockPos) { public RenderSection getSectionAtBlockPos(int x, int y, int z) { int i = x >> 4; - int j = (y - this.level.getMinBuildHeight()) >> 4; + int j = (y - this.level.getMinY()) >> 4; int k = z >> 4; return this.getSectionAtSectionPos(i, j, k); diff --git a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java index c8fed57c5..6030c4859 100644 --- a/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/WorldRenderer.java @@ -2,19 +2,14 @@ import com.google.common.collect.Sets; import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.SheetedDecalTextureGenerator; -import com.mojang.blaze3d.vertex.VertexConsumer; -import com.mojang.blaze3d.vertex.VertexMultiConsumer; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderBuffers; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.culling.Frustum; -import net.minecraft.client.resources.model.ModelBakery; import net.minecraft.core.BlockPos; import net.minecraft.core.SectionPos; import net.minecraft.server.level.BlockDestructionProgress; @@ -26,18 +21,18 @@ import net.vulkanmod.render.PipelineManager; import net.vulkanmod.render.chunk.buffer.DrawBuffers; import net.vulkanmod.render.chunk.build.RenderRegionBuilder; -import net.vulkanmod.render.chunk.build.task.TaskDispatcher; import net.vulkanmod.render.chunk.build.task.ChunkTask; +import net.vulkanmod.render.chunk.build.task.TaskDispatcher; import net.vulkanmod.render.chunk.graph.SectionGraph; import net.vulkanmod.render.profiling.BuildTimeProfiler; import net.vulkanmod.render.profiling.Profiler; import net.vulkanmod.render.vertex.TerrainRenderType; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; +import net.vulkanmod.vulkan.memory.MemoryTypes; import net.vulkanmod.vulkan.memory.buffer.Buffer; import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; import net.vulkanmod.vulkan.memory.buffer.IndirectBuffer; -import net.vulkanmod.vulkan.memory.MemoryTypes; import net.vulkanmod.vulkan.shader.GraphicsPipeline; import net.vulkanmod.vulkan.texture.VTextureSelector; import org.jetbrains.annotations.Nullable; @@ -50,10 +45,14 @@ public class WorldRenderer { private static WorldRenderer INSTANCE; private final Minecraft minecraft; + private final RenderBuffers renderBuffers; + private final Set globalBlockEntities = Sets.newHashSet(); + private final TaskDispatcher taskDispatcher; + private final List onAllChangedCallbacks = new ObjectArrayList<>(); + public RenderRegionBuilder renderRegionCache; + IndirectBuffer[] indirectBuffers; private ClientLevel level; private int renderDistance; - private final RenderBuffers renderBuffers; - private Vec3 cameraPos; private int lastCameraSectionX; private int lastCameraSectionY; @@ -63,26 +62,13 @@ public class WorldRenderer { private float lastCameraZ; private float lastCamRotX; private float lastCamRotY; - private SectionGrid sectionGrid; - private SectionGraph sectionGraph; private boolean graphNeedsUpdate; - - private final Set globalBlockEntities = Sets.newHashSet(); - - private final TaskDispatcher taskDispatcher; - private double xTransparentOld; private double yTransparentOld; private double zTransparentOld; - IndirectBuffer[] indirectBuffers; - - public RenderRegionBuilder renderRegionCache; - - private final List onAllChangedCallbacks = new ObjectArrayList<>(); - private WorldRenderer(RenderBuffers renderBuffers) { this.minecraft = Minecraft.getInstance(); this.renderBuffers = renderBuffers; @@ -98,17 +84,6 @@ private WorldRenderer(RenderBuffers renderBuffers) { }); } - private void allocateIndirectBuffers() { - if (this.indirectBuffers != null) - Arrays.stream(this.indirectBuffers).forEach(Buffer::scheduleFree); - - this.indirectBuffers = new IndirectBuffer[Renderer.getFramesNum()]; - - for (int i = 0; i < this.indirectBuffers.length; ++i) { - this.indirectBuffers[i] = new IndirectBuffer(1000000, MemoryTypes.HOST_MEM); - } - } - public static WorldRenderer init(RenderBuffers renderBuffers) { if (INSTANCE != null) return INSTANCE; @@ -124,10 +99,47 @@ public static ClientLevel getLevel() { return INSTANCE.level; } + public void setLevel(@Nullable ClientLevel level) { + this.lastCameraX = Float.MIN_VALUE; + this.lastCameraY = Float.MIN_VALUE; + this.lastCameraZ = Float.MIN_VALUE; + this.lastCameraSectionX = Integer.MIN_VALUE; + this.lastCameraSectionY = Integer.MIN_VALUE; + this.lastCameraSectionZ = Integer.MIN_VALUE; + +// this.entityRenderDispatcher.setLevel(level); + this.level = level; + ChunkStatusMap.createInstance(renderDistance); + if (level != null) { + this.allChanged(); + } else { + if (this.sectionGrid != null) { + this.sectionGrid.freeAllBuffers(); + this.sectionGrid = null; + } + + this.taskDispatcher.stopThreads(); + + this.graphNeedsUpdate = true; + } + + } + public static Vec3 getCameraPos() { return INSTANCE.cameraPos; } + private void allocateIndirectBuffers() { + if (this.indirectBuffers != null) + Arrays.stream(this.indirectBuffers).forEach(Buffer::scheduleFree); + + this.indirectBuffers = new IndirectBuffer[Renderer.getFramesNum()]; + + for (int i = 0; i < this.indirectBuffers.length; ++i) { + this.indirectBuffers[i] = new IndirectBuffer(1000000, MemoryTypes.HOST_MEM); + } + } + private void benchCallback() { BuildTimeProfiler.runBench(this.graphNeedsUpdate || !this.taskDispatcher.isIdle()); } @@ -143,7 +155,7 @@ public void setupRenderer(Camera camera, Frustum frustum, boolean isCapturedFrus this.allChanged(); } - this.level.getProfiler().push("camera"); + profiler.push("camera"); float cameraX = (float) cameraPos.x(); float cameraY = (float) cameraPos.y(); float cameraZ = (float) cameraPos.z(); @@ -163,10 +175,7 @@ public void setupRenderer(Camera camera, Frustum frustum, boolean isCapturedFrus double entityDistanceScaling = this.minecraft.options.entityDistanceScaling().get(); Entity.setViewScale(Mth.clamp((double) this.renderDistance / 8.0D, 1.0D, 2.5D) * entityDistanceScaling); - this.level.getProfiler().popPush("cull"); - this.minecraft.getProfiler().popPush("culling"); - - this.minecraft.getProfiler().popPush("update"); + profiler.push("culling"); boolean cameraMoved = false; float d_xRot = Math.abs(camera.getXRot() - this.lastCamRotX); @@ -176,6 +185,9 @@ public void setupRenderer(Camera camera, Frustum frustum, boolean isCapturedFrus cameraMoved |= cameraX != this.lastCameraX || cameraY != this.lastCameraY || cameraZ != this.lastCameraZ; this.graphNeedsUpdate |= cameraMoved; + profiler.pop(); // culling + profiler.push("update"); + if (!isCapturedFrustum) { //Debug // this.graphNeedsUpdate = true; @@ -194,13 +206,12 @@ public void setupRenderer(Camera camera, Frustum frustum, boolean isCapturedFrus this.indirectBuffers[Renderer.getCurrentFrame()].reset(); - this.minecraft.getProfiler().pop(); - profiler.pop(); + profiler.pop(); // update + profiler.pop(); // camera + profiler.pop(); // Setup_Renderer } public void uploadSections() { - this.minecraft.getProfiler().push("upload"); - Profiler profiler = Profiler.getMainProfiler(); profiler.push("Uploads"); @@ -213,8 +224,6 @@ public void uploadSections() { } profiler.pop(); - - this.minecraft.getProfiler().pop(); } public boolean isSectionCompiled(BlockPos blockPos) { @@ -254,32 +263,6 @@ public void allChanged() { } } - public void setLevel(@Nullable ClientLevel level) { - this.lastCameraX = Float.MIN_VALUE; - this.lastCameraY = Float.MIN_VALUE; - this.lastCameraZ = Float.MIN_VALUE; - this.lastCameraSectionX = Integer.MIN_VALUE; - this.lastCameraSectionY = Integer.MIN_VALUE; - this.lastCameraSectionZ = Integer.MIN_VALUE; - -// this.entityRenderDispatcher.setLevel(level); - this.level = level; - ChunkStatusMap.createInstance(renderDistance); - if (level != null) { - this.allChanged(); - } else { - if (this.sectionGrid != null) { - this.sectionGrid.freeAllBuffers(); - this.sectionGrid = null; - } - - this.taskDispatcher.stopThreads(); - - this.graphNeedsUpdate = true; - } - - } - public void addOnAllChangedCallback(Runnable runnable) { this.onAllChangedCallbacks.add(runnable); } @@ -290,12 +273,13 @@ public void clearOnAllChangedCallbacks() { public void renderSectionLayer(RenderType renderType, double camX, double camY, double camZ, Matrix4f modelView, Matrix4f projection) { TerrainRenderType terrainRenderType = TerrainRenderType.get(renderType); + Profiler profiler = Profiler.getMainProfiler(); + profiler.push("render_" + terrainRenderType.name()); renderType.setupRenderState(); - this.sortTranslucentSections(camX, camY, camZ); + this.sortTranslucentSections(profiler, camX, camY, camZ); - this.minecraft.getProfiler().push("filterempty"); - this.minecraft.getProfiler().popPush(() -> "render_" + renderType); + profiler.push("filterempty"); final boolean isTranslucent = terrainRenderType == TerrainRenderType.TRANSLUCENT; final boolean indirectDraw = Initializer.CONFIG.indirectDraw; @@ -347,12 +331,13 @@ public void renderSectionLayer(RenderType renderType, double camX, double camY, renderer.pushConstants(pipeline); } - this.minecraft.getProfiler().pop(); + profiler.pop(); renderType.clearRenderState(); + profiler.pop(); } - private void sortTranslucentSections(double camX, double camY, double camZ) { - this.minecraft.getProfiler().push("translucent_sort"); + private void sortTranslucentSections(Profiler profiler, double camX, double camY, double camZ) { + profiler.push("translucent_sort"); double d0 = camX - this.xTransparentOld; double d1 = camY - this.yTransparentOld; double d2 = camZ - this.zTransparentOld; @@ -374,43 +359,12 @@ private void sortTranslucentSections(double camX, double camY, double camZ) { } } - this.minecraft.getProfiler().pop(); + profiler.pop(); } public void renderBlockEntities(PoseStack poseStack, double camX, double camY, double camZ, Long2ObjectMap> destructionProgress, float gameTime) { - Profiler profiler = Profiler.getMainProfiler(); - profiler.pop(); - profiler.push("Block-entities"); - - MultiBufferSource bufferSource = this.renderBuffers.bufferSource(); - - for (RenderSection renderSection : this.sectionGraph.getBlockEntitiesSections()) { - List list = renderSection.getCompiledSection().getBlockEntities(); - if (!list.isEmpty()) { - for (BlockEntity blockEntity : list) { - BlockPos blockPos = blockEntity.getBlockPos(); - MultiBufferSource bufferSource1 = bufferSource; - poseStack.pushPose(); - poseStack.translate((double) blockPos.getX() - camX, (double) blockPos.getY() - camY, (double) blockPos.getZ() - camZ); - SortedSet sortedset = destructionProgress.get(blockPos.asLong()); - if (sortedset != null && !sortedset.isEmpty()) { - int j1 = sortedset.last().getProgress(); - if (j1 >= 0) { - PoseStack.Pose pose = poseStack.last(); - VertexConsumer vertexconsumer = new SheetedDecalTextureGenerator(this.renderBuffers.crumblingBufferSource().getBuffer(ModelBakery.DESTROY_TYPES.get(j1)), pose, 1.0f); - bufferSource1 = (renderType) -> { - VertexConsumer vertexConsumer2 = bufferSource.getBuffer(renderType); - return renderType.affectsCrumbling() ? VertexMultiConsumer.create(vertexconsumer, vertexConsumer2) : vertexConsumer2; - }; - } - } - - this.minecraft.getBlockEntityRenderDispatcher().render(blockEntity, gameTime, poseStack, bufferSource1); - poseStack.popPose(); - } - } - } + // TODO: reimplement block entity rendering using the new render-state based dispatcher } public void scheduleGraphUpdate() { diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java b/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java index c2c02db66..e2df45537 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/AreaBuffer.java @@ -3,7 +3,9 @@ import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap; import net.vulkanmod.Initializer; import net.vulkanmod.render.chunk.util.Util; -import net.vulkanmod.vulkan.memory.*; +import net.vulkanmod.vulkan.memory.MemoryManager; +import net.vulkanmod.vulkan.memory.MemoryType; +import net.vulkanmod.vulkan.memory.MemoryTypes; import net.vulkanmod.vulkan.memory.buffer.Buffer; import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; import net.vulkanmod.vulkan.memory.buffer.VertexBuffer; @@ -23,11 +25,9 @@ public class AreaBuffer { private final Int2ReferenceOpenHashMap usedSegments = new Int2ReferenceOpenHashMap<>(); Segment first, last; - - private Buffer buffer; - int size, used = 0; int segments = 0; + private Buffer buffer; public AreaBuffer(Usage usage, int elementCount, int elementSize) { this.usage = usage.usage; @@ -140,8 +140,7 @@ public Segment reallocate(int uploadSize) { if (last.isFree()) { last.size += increment; - } - else { + } else { int offset = last.offset + last.size; Segment segment = new Segment(offset, newSize - offset); segments++; @@ -349,6 +348,17 @@ public int getUsed() { return used; } + public enum Usage { + VERTEX(0), + INDEX(1); + + final int usage; + + Usage(int i) { + usage = i; + } + } + public static class Segment { int offset, size; boolean free = true; @@ -384,15 +394,4 @@ public void bindNext(Segment s) { } - public enum Usage { - VERTEX(0), - INDEX(1); - - final int usage; - - Usage(int i) { - usage = i; - } - } - } diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java index 24f3c9550..eb005c518 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawBuffers.java @@ -26,22 +26,19 @@ public class DrawBuffers { public static final int VERTEX_SIZE = PipelineManager.terrainVertexFormat.getVertexSize(); public static final int INDEX_SIZE = Short.BYTES; - + // TODO: refactor + public static final float POS_OFFSET = PipelineManager.terrainVertexFormat == CustomVertexFormat.COMPRESSED_TERRAIN ? 4.0f : 0.0f; private static final int CMD_STRIDE = 32; - private static final long cmdBufferPtr = MemoryUtil.nmemAlignedAlloc(CMD_STRIDE, (long) ChunkAreaManager.AREA_SIZE * QuadFacing.COUNT * CMD_STRIDE); - + final int[] sectionIndices = new int[512]; + final int[] masks = new int[512]; private final int index; private final Vector3i origin; private final int minHeight; - - private boolean allocated = false; - AreaBuffer indexBuffer; private final EnumMap vertexBuffers = new EnumMap<>(TerrainRenderType.class); - + AreaBuffer indexBuffer; long drawParamsPtr; - final int[] sectionIndices = new int[512]; - final int[] masks = new int[512]; + private boolean allocated = false; //Need ugly minHeight Parameter to fix custom world heights (exceeding 384 Blocks in total) public DrawBuffers(int index, Vector3i origin, int minHeight) { @@ -140,9 +137,6 @@ private int encodeSectionOffset(int xOffset, int yOffset, int zOffset) { return yOffset1 << 16 | zOffset1 << 8 | xOffset1; } - // TODO: refactor - public static final float POS_OFFSET = PipelineManager.terrainVertexFormat == CustomVertexFormat.COMPRESSED_TERRAIN ? 4.0f : 0.0f; - private void updateChunkAreaOrigin(VkCommandBuffer commandBuffer, Pipeline pipeline, double camX, double camY, double camZ, MemoryStack stack) { float xOffset = (float) ((this.origin.x) + POS_OFFSET - camX); float yOffset = (float) ((this.origin.y) + POS_OFFSET - camY); @@ -218,8 +212,7 @@ public void buildDrawBatchesIndirect(Vec3 cameraPos, IndirectBuffer indirectBuff } } - } - else { + } else { for (var iterator = queue.iterator(isTranslucent); iterator.hasNext(); ) { final RenderSection section = iterator.next(); @@ -317,8 +310,7 @@ public void buildDrawBatchesDirect(Vec3 cameraPos, StaticQueue qu } } - } - else { + } else { final int facing = 6; final long facingOffset = facing * DrawParametersBuffer.STRIDE; drawParamsBasePtr += facingOffset; diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawParametersBuffer.java b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawParametersBuffer.java index f26c2420d..4f4dc38ac 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/DrawParametersBuffer.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/DrawParametersBuffer.java @@ -6,13 +6,11 @@ import org.lwjgl.system.MemoryUtil; public abstract class DrawParametersBuffer { + public static final long STRIDE = 16; static final long INDEX_COUNT_OFFSET = 0; static final long FIRST_INDEX_OFFSET = 4; static final long VERTEX_OFFSET_OFFSET = 8; static final long BASE_INSTANCE_OFFSET = 12; - - public static final long STRIDE = 16; - static final int SECTIONS = ChunkAreaManager.AREA_SIZE; static final int FACINGS = 7; diff --git a/src/main/java/net/vulkanmod/render/chunk/buffer/UploadManager.java b/src/main/java/net/vulkanmod/render/chunk/buffer/UploadManager.java index 5ab8bee72..fb032396c 100644 --- a/src/main/java/net/vulkanmod/render/chunk/buffer/UploadManager.java +++ b/src/main/java/net/vulkanmod/render/chunk/buffer/UploadManager.java @@ -20,16 +20,14 @@ public class UploadManager { public static UploadManager INSTANCE; + Queue queue = DeviceManager.getTransferQueue(); + CommandPool.CommandBuffer commandBuffer; + LongOpenHashSet dstBuffers = new LongOpenHashSet(); public static void createInstance() { INSTANCE = new UploadManager(); } - Queue queue = DeviceManager.getTransferQueue(); - CommandPool.CommandBuffer commandBuffer; - - LongOpenHashSet dstBuffers = new LongOpenHashSet(); - public void submitUploads() { if (this.commandBuffer == null) return; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java index 94a19358b..bb6bb60a9 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegion.java @@ -1,6 +1,5 @@ package net.vulkanmod.render.chunk.build; -import net.fabricmc.fabric.api.rendering.data.v1.RenderAttachedBlockView; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -26,7 +25,7 @@ import java.util.Map; import java.util.function.Function; -public class RenderRegion implements BlockAndTintGetter, RenderAttachedBlockView { +public class RenderRegion implements BlockAndTintGetter { public static final int WIDTH = 3; public static final int SIZE = WIDTH * WIDTH * WIDTH; @@ -45,13 +44,10 @@ public class RenderRegion implements BlockAndTintGetter, RenderAttachedBlockView private final PalettedContainer[] blockDataContainers; private final BlockState[] blockData; private final DataLayer[][] lightData; - - private BiomeData biomeData; - private TintCache tintCache; - private final Map blockEntityMap; - private final Function blockStateGetter; + private BiomeData biomeData; + private TintCache tintCache; RenderRegion(Level level, int x, int y, int z, PalettedContainer[] blockData, DataLayer[][] lightData, BiomeData biomeData, Map blockEntityMap) { @@ -105,7 +101,7 @@ public void loadBlockStates() { int tMaxZ = Math.min(maxZ, absBlockZ + 16); loadSectionBlockStates(container, blockData, - tMinX, tMinY, tMinZ, tMaxX, tMaxY, tMaxZ); + tMinX, tMinY, tMinZ, tMaxX, tMaxY, tMaxZ); } } @@ -194,13 +190,18 @@ public int getBlockTint(BlockPos blockPos, ColorResolver colorResolver) { } public int getMinBuildHeight() { - return this.level.getMinBuildHeight(); + return this.level.getMinY(); } public int getHeight() { return this.level.getHeight(); } + @Override + public int getMinY() { + return this.level.getMinY(); + } + public int getSectionIdx(int secX, int secY, int secZ) { return WIDTH * ((WIDTH * secY) + secZ) + secX; } @@ -237,8 +238,7 @@ public BlockState debugBlockState(BlockPos blockPos) { BlockState blockState = null; if (y == 60) { blockState = Blocks.BARRIER.defaultBlockState(); - } - else if (y == 70) { + } else if (y == 70) { blockState = DebugLevelSource.getBlockStateFor(x, z); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java index dc3317636..b3148e219 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/RenderRegionBuilder.java @@ -44,7 +44,7 @@ public RenderRegion createRegion(Level level, int secX, int secY, int secZ) { long biomeZoomSeed = BiomeManagerExtended.of(level.getBiomeManager()).getBiomeZoomSeed(); BiomeData biomeData = new BiomeData(biomeZoomSeed, minSecX, minSecY, minSecZ); - final int minHeightSec = level.getMinBuildHeight() >> 4; + final int minHeightSec = level.getMinY() >> 4; for (int x = minSecX; x <= maxSecX; ++x) { for (int z = minSecZ; z <= maxSecZ; ++z) { LevelChunk levelChunk1 = getLevelChunk(level, x, z); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/UploadBuffer.java b/src/main/java/net/vulkanmod/render/chunk/build/UploadBuffer.java index 3254b19c4..571d23d38 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/UploadBuffer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/UploadBuffer.java @@ -2,7 +2,6 @@ import net.vulkanmod.render.chunk.cull.QuadFacing; import net.vulkanmod.render.chunk.util.BufferUtil; -import net.vulkanmod.render.vertex.TerrainBufferBuilder; import net.vulkanmod.render.vertex.TerrainBuilder; import org.lwjgl.system.MemoryUtil; @@ -30,15 +29,13 @@ public UploadBuffer(TerrainBuilder terrainBuilder, TerrainBuilder.DrawState draw this.vertexBuffers[i] = BufferUtil.clone(bufferBuilder.getBuffer()); } } - } - else { + } else { this.vertexBuffers = null; } if (!drawState.sequentialIndex()) { this.indexBuffer = BufferUtil.clone(terrainBuilder.getIndexBuffer()); - } - else { + } else { this.indexBuffer = null; } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/biome/BiomeData.java b/src/main/java/net/vulkanmod/render/chunk/build/biome/BiomeData.java index 166f4b3a8..0c03639ac 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/biome/BiomeData.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/biome/BiomeData.java @@ -14,10 +14,8 @@ public class BiomeData { private static final int ZOOM_LENGTH = 4; private static final int BIOMES_PER_SECTION = 4 * 4 * 4; private static final int SIZE = RenderRegion.SIZE * BIOMES_PER_SECTION; - - Biome[] biomes = new Biome[SIZE]; private final long biomeZoomSeed; - + Biome[] biomes = new Biome[SIZE]; int secX, secY, secZ; // Cached cell offsets @@ -30,11 +28,41 @@ public BiomeData(long biomeZoomSeed, int secX, int secY, int secZ) { this.secZ = secZ; } + private static Vector3f computeCellOffset(long l, int cellX, int cellY, int cellZ) { + long seed; + seed = LinearCongruentialGenerator.next(l, cellX); + seed = LinearCongruentialGenerator.next(seed, cellY); + seed = LinearCongruentialGenerator.next(seed, cellZ); + seed = LinearCongruentialGenerator.next(seed, cellX); + seed = LinearCongruentialGenerator.next(seed, cellY); + seed = LinearCongruentialGenerator.next(seed, cellZ); + + float xOffset = getFiddle(seed); + seed = LinearCongruentialGenerator.next(seed, l); + float yOffset = getFiddle(seed); + seed = LinearCongruentialGenerator.next(seed, l); + float zOffset = getFiddle(seed); + + return new Vector3f(xOffset, yOffset, zOffset); + } + + private static float getFiddle(long l) { + float d = Math.floorMod(l >> 24, 1024) * (1.0f / 1024.0f); + return (d - 0.5f) * 0.9f; + } + + private static int getRelativeSectionIdx(int x, int y, int z) { + return ((x * RenderRegion.WIDTH * RenderRegion.WIDTH) + (y * RenderRegion.WIDTH) + z) * BIOMES_PER_SECTION; + } + + private static int getRelativeIdx(int x, int y, int z) { + return (x * ZOOM_LENGTH * ZOOM_LENGTH) + (y * ZOOM_LENGTH) + z; + } + public void getBiomeData(Level level, LevelChunkSection chunkSection, int secX, int secY, int secZ) { Biome defaultValue = level.registryAccess() - .registryOrThrow(Registries.BIOME) - .getHolderOrThrow(Biomes.PLAINS) - .value(); + .lookupOrThrow(Registries.BIOME) + .getValueOrThrow(Biomes.PLAINS); int baseIdx = getRelativeSectionIdx(secX, secY, secZ); @@ -46,9 +74,8 @@ public void getBiomeData(Level level, LevelChunkSection chunkSection, int secX, if (chunkSection != null) { biomes[idx] = chunkSection.getNoiseBiome(x, y, z) - .value(); - } - else { + .value(); + } else { biomes[idx] = defaultValue; } @@ -119,35 +146,4 @@ private Vector3f getOffset(int baseIndex, int cellX, int cellY, int cellZ) { return this.offsets[idx]; } - private static Vector3f computeCellOffset(long l, int cellX, int cellY, int cellZ) { - long seed; - seed = LinearCongruentialGenerator.next(l, cellX); - seed = LinearCongruentialGenerator.next(seed, cellY); - seed = LinearCongruentialGenerator.next(seed, cellZ); - seed = LinearCongruentialGenerator.next(seed, cellX); - seed = LinearCongruentialGenerator.next(seed, cellY); - seed = LinearCongruentialGenerator.next(seed, cellZ); - - float xOffset = getFiddle(seed); - seed = LinearCongruentialGenerator.next(seed, l); - float yOffset = getFiddle(seed); - seed = LinearCongruentialGenerator.next(seed, l); - float zOffset = getFiddle(seed); - - return new Vector3f(xOffset, yOffset, zOffset); - } - - private static float getFiddle(long l) { - float d = Math.floorMod(l >> 24, 1024) * (1.0f / 1024.0f); - return (d - 0.5f) * 0.9f; - } - - private static int getRelativeSectionIdx(int x, int y, int z) { - return ((x * RenderRegion.WIDTH * RenderRegion.WIDTH) + (y * RenderRegion.WIDTH) + z) * BIOMES_PER_SECTION; - } - - private static int getRelativeIdx(int x, int y, int z) { - return (x * ZOOM_LENGTH * ZOOM_LENGTH) + (y * ZOOM_LENGTH) + z; - } - } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/color/BlockColorRegistry.java b/src/main/java/net/vulkanmod/render/chunk/build/color/BlockColorRegistry.java index b8ec0ca39..a76e56e63 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/color/BlockColorRegistry.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/color/BlockColorRegistry.java @@ -6,16 +6,16 @@ public class BlockColorRegistry { - private final Reference2ReferenceOpenHashMap map = new Reference2ReferenceOpenHashMap<>(); + private final Reference2ReferenceOpenHashMap map = new Reference2ReferenceOpenHashMap<>(); - public void register(BlockColor blockColor, Block... blocks) { - for (Block block : blocks) { - this.map.put(block, blockColor); - } - } + public void register(BlockColor blockColor, Block... blocks) { + for (Block block : blocks) { + this.map.put(block, blockColor); + } + } - public BlockColor getBlockColor(Block block) { - return this.map.get(block); - } + public BlockColor getBlockColor(Block block) { + return this.map.get(block); + } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/color/BoxBlur.java b/src/main/java/net/vulkanmod/render/chunk/build/color/BoxBlur.java index f86333de7..4360d9780 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/color/BoxBlur.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/color/BoxBlur.java @@ -16,7 +16,7 @@ public static void horizontalBlur(int[] src, int[] dst, int y0, int width, int f int r = 0, g = 0, b = 0; //init accumulator - for(int x = 0; x < x0 + 1 + filterRadius; ++x) { + for (int x = 0; x < x0 + 1 + filterRadius; ++x) { color = src[getIdx(x, y, totalWidth)]; r += unpackR(color); g += unpackG(color); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java b/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java index e31cc965e..320c57fbd 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/color/TintCache.java @@ -62,8 +62,7 @@ public void init(BiomeData biomeData, int blendRadius, int secX, int secY, int s } this.temp = new int[size]; - } - else { + } else { for (Layer[] layers : layers.values()) { for (Layer layer : layers) { layer.invalidate(); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java deleted file mode 100644 index e2a335109..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/VulkanModRenderer.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.vulkanmod.render.chunk.build.frapi; - -import java.util.HashMap; - -import net.minecraft.resources.ResourceLocation; - -import net.fabricmc.fabric.api.renderer.v1.Renderer; -import net.fabricmc.fabric.api.renderer.v1.material.MaterialFinder; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.fabricmc.fabric.api.renderer.v1.mesh.MeshBuilder; -import net.vulkanmod.render.chunk.build.frapi.material.MaterialFinderImpl; -import net.vulkanmod.render.chunk.build.frapi.material.RenderMaterialImpl; -import net.vulkanmod.render.chunk.build.frapi.mesh.MeshBuilderImpl; - -/** - * The Fabric default renderer implementation. Supports all - * features defined in the API except shaders and offers no special materials. - */ -public class VulkanModRenderer implements Renderer { - public static final VulkanModRenderer INSTANCE = new VulkanModRenderer(); - - public static final RenderMaterial MATERIAL_STANDARD = INSTANCE.materialFinder().find(); - - static { - INSTANCE.registerMaterial(RenderMaterial.MATERIAL_STANDARD, MATERIAL_STANDARD); - } - - private final HashMap materialMap = new HashMap<>(); - - private VulkanModRenderer() {} - - @Override - public MeshBuilder meshBuilder() { - return new MeshBuilderImpl(); - } - - @Override - public MaterialFinder materialFinder() { - return new MaterialFinderImpl(); - } - - @Override - public RenderMaterial materialById(ResourceLocation id) { - return materialMap.get(id); - } - - @Override - public boolean registerMaterial(ResourceLocation id, RenderMaterial material) { - if (materialMap.containsKey(id)) return false; - - // cast to prevent acceptance of impostor implementations - materialMap.put(id, (RenderMaterialImpl) material); - return true; - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/ColorHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/ColorHelper.java deleted file mode 100644 index 2723331b2..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/ColorHelper.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.helper; - -import java.nio.ByteOrder; - -/** - * Static routines of general utility for renderer implementations. - * Renderers are not required to use these helpers, but they were - * designed to be usable without the default renderer. - */ -public abstract class ColorHelper { - private ColorHelper() { } - - private static final boolean BIG_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN; - - /** Component-wise multiply. Components need to be in same order in both inputs! */ - public static int multiplyColor(int color1, int color2) { - if (color1 == -1) { - return color2; - } else if (color2 == -1) { - return color1; - } - - final int alpha = ((color1 >>> 24) & 0xFF) * ((color2 >>> 24) & 0xFF) / 0xFF; - final int red = ((color1 >>> 16) & 0xFF) * ((color2 >>> 16) & 0xFF) / 0xFF; - final int green = ((color1 >>> 8) & 0xFF) * ((color2 >>> 8) & 0xFF) / 0xFF; - final int blue = (color1 & 0xFF) * (color2 & 0xFF) / 0xFF; - - return (alpha << 24) | (red << 16) | (green << 8) | blue; - } - - /** Multiplies three lowest components by shade. High byte (usually alpha) unchanged. */ - public static int multiplyRGB(int color, float shade) { - final int alpha = ((color >>> 24) & 0xFF); - final int red = (int) (((color >>> 16) & 0xFF) * shade); - final int green = (int) (((color >>> 8) & 0xFF) * shade); - final int blue = (int) ((color & 0xFF) * shade); - - return (alpha << 24) | (red << 16) | (green << 8) | blue; - } - - /** - * Component-wise max. - */ - public static int maxBrightness(int b0, int b1) { - if (b0 == 0) return b1; - if (b1 == 0) return b0; - - return Math.max(b0 & 0xFFFF, b1 & 0xFFFF) | Math.max(b0 & 0xFFFF0000, b1 & 0xFFFF0000); - } - - /* - Renderer color format: ARGB (0xAARRGGBB) - Vanilla color format (little endian): ABGR (0xAABBGGRR) - Vanilla color format (big endian): RGBA (0xRRGGBBAA) - - Why does the vanilla color format change based on endianness? - See VertexConsumer#quad. Quad data is loaded as integers into - a native byte order buffer. Color is read directly from bytes - 12, 13, 14 of each vertex. A different byte order will yield - different results. - - The renderer always uses ARGB because the API color methods - always consume and return ARGB. Vanilla block and item colors - also use ARGB. - */ - - /** - * Converts from ARGB color to ABGR color if little endian or RGBA color if big endian. - */ - public static int toVanillaColor(int color) { - if (color == -1) { - return -1; - } - - if (BIG_ENDIAN) { - // ARGB to RGBA - return ((color & 0x00FFFFFF) << 8) | ((color & 0xFF000000) >>> 24); - } else { - // ARGB to ABGR - return (color & 0xFF00FF00) | ((color & 0x00FF0000) >>> 16) | ((color & 0x000000FF) << 16); - } - } - - /** - * Converts to ARGB color from ABGR color if little endian or RGBA color if big endian. - */ - public static int fromVanillaColor(int color) { - if (color == -1) { - return -1; - } - - if (BIG_ENDIAN) { - // RGBA to ARGB - return ((color & 0xFFFFFF00) >>> 8) | ((color & 0x000000FF) << 24); - } else { - // ABGR to ARGB - return (color & 0xFF00FF00) | ((color & 0x00FF0000) >>> 16) | ((color & 0x000000FF) << 16); - } - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/GeometryHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/GeometryHelper.java deleted file mode 100644 index 66e8a805e..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/GeometryHelper.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.helper; - -import static net.minecraft.util.Mth.equal; - -import org.joml.Vector3f; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.core.Direction; -import net.minecraft.core.Direction.Axis; -import net.minecraft.core.Direction.AxisDirection; - -/** - * Static routines of general utility for renderer implementations. - * Renderers are not required to use these helpers, but they were - * designed to be usable without the default renderer. - */ -public abstract class GeometryHelper { - private GeometryHelper() { } - - /** set when a quad touches all four corners of a unit cube. */ - public static final int CUBIC_FLAG = 1; - - /** set when a quad is parallel to (but not necessarily on) a its light face. */ - public static final int AXIS_ALIGNED_FLAG = CUBIC_FLAG << 1; - - /** set when a quad is coplanar with its light face. Implies {@link #AXIS_ALIGNED_FLAG} */ - public static final int LIGHT_FACE_FLAG = AXIS_ALIGNED_FLAG << 1; - - /** how many bits quad header encoding should reserve for encoding geometry flags. */ - public static final int FLAG_BIT_COUNT = 3; - - private static final float EPS_MIN = 0.0001f; - private static final float EPS_MAX = 1.0f - EPS_MIN; - - /** - * Analyzes the quad and returns a value with some combination - * of {@link #AXIS_ALIGNED_FLAG}, {@link #LIGHT_FACE_FLAG} and {@link #CUBIC_FLAG}. - * Intended use is to optimize lighting when the geometry is regular. - * Expects convex quads with all points co-planar. - */ - public static int computeShapeFlags(QuadView quad) { - Direction lightFace = quad.lightFace(); - int bits = 0; - - if (isQuadParallelToFace(lightFace, quad)) { - bits |= AXIS_ALIGNED_FLAG; - - if (isParallelQuadOnFace(lightFace, quad)) { - bits |= LIGHT_FACE_FLAG; - } - } - - if (isQuadCubic(lightFace, quad)) { - bits |= CUBIC_FLAG; - } - - return bits; - } - - /** - * Returns true if quad is parallel to the given face. - * Does not validate quad winding order. - * Expects convex quads with all points co-planar. - */ - public static boolean isQuadParallelToFace(Direction face, QuadView quad) { - int i = face.getAxis().ordinal(); - final float val = quad.posByIndex(0, i); - return equal(val, quad.posByIndex(1, i)) && equal(val, quad.posByIndex(2, i)) && equal(val, quad.posByIndex(3, i)); - } - - /** - * True if quad - already known to be parallel to a face - is actually coplanar with it. - * For compatibility with vanilla resource packs, also true if quad is outside the face. - * - *

Test will be unreliable if not already parallel, use {@link #isQuadParallelToFace(Direction, QuadView)} - * for that purpose. Expects convex quads with all points co-planar. - */ - public static boolean isParallelQuadOnFace(Direction lightFace, QuadView quad) { - final float x = quad.posByIndex(0, lightFace.getAxis().ordinal()); - return lightFace.getAxisDirection() == AxisDirection.POSITIVE ? x >= EPS_MAX : x <= EPS_MIN; - } - - /** - * Returns true if quad is truly a quad (not a triangle) and fills a full block cross-section. - * If known to be true, allows use of a simpler/faster AO lighting algorithm. - * - *

Does not check if quad is actually coplanar with the light face, nor does it check that all - * quad vertices are coplanar with each other. - * - *

Expects convex quads with all points co-planar. - */ - public static boolean isQuadCubic(Direction lightFace, QuadView quad) { - int a, b; - - switch (lightFace) { - case EAST: - case WEST: - a = 1; - b = 2; - break; - case UP: - case DOWN: - a = 0; - b = 2; - break; - case SOUTH: - case NORTH: - a = 1; - b = 0; - break; - default: - // handle WTF case - return false; - } - - return confirmSquareCorners(a, b, quad); - } - - /** - * Used by {@link #isQuadCubic(Direction, QuadView)}. - * True if quad touches all four corners of unit square. - * - *

For compatibility with resource packs that contain models with quads exceeding - * block boundaries, considers corners outside the block to be at the corners. - */ - private static boolean confirmSquareCorners(int aCoordinate, int bCoordinate, QuadView quad) { - int flags = 0; - - for (int i = 0; i < 4; i++) { - final float a = quad.posByIndex(i, aCoordinate); - final float b = quad.posByIndex(i, bCoordinate); - - if (a <= EPS_MIN) { - if (b <= EPS_MIN) { - flags |= 1; - } else if (b >= EPS_MAX) { - flags |= 2; - } else { - return false; - } - } else if (a >= EPS_MAX) { - if (b <= EPS_MIN) { - flags |= 4; - } else if (b >= EPS_MAX) { - flags |= 8; - } else { - return false; - } - } else { - return false; - } - } - - return flags == 15; - } - - /** - * Identifies the face to which the quad is most closely aligned. - * This mimics the value that {@link BakedQuad#getDirection()} returns, and is - * used in the vanilla renderer for all diffuse lighting. - * - *

Derived from the quad face normal and expects convex quads with all points co-planar. - */ - public static Direction lightFace(QuadView quad) { - final Vector3f normal = quad.faceNormal(); - switch (GeometryHelper.longestAxis(normal)) { - case X: - return normal.x() > 0 ? Direction.EAST : Direction.WEST; - - case Y: - return normal.y() > 0 ? Direction.UP : Direction.DOWN; - - case Z: - return normal.z() > 0 ? Direction.SOUTH : Direction.NORTH; - - default: - // handle WTF case - return Direction.UP; - } - } - - /** - * Simple 4-way compare, doesn't handle NaN values. - */ - public static float min(float a, float b, float c, float d) { - final float x = a < b ? a : b; - final float y = c < d ? c : d; - return x < y ? x : y; - } - - /** - * Simple 4-way compare, doesn't handle NaN values. - */ - public static float max(float a, float b, float c, float d) { - final float x = a > b ? a : b; - final float y = c > d ? c : d; - return x > y ? x : y; - } - - /** - * @see #longestAxis(float, float, float) - */ - public static Axis longestAxis(Vector3f vec) { - return longestAxis(vec.x(), vec.y(), vec.z()); - } - - /** - * Identifies the largest (max absolute magnitude) component (X, Y, Z) in the given vector. - */ - public static Axis longestAxis(float normalX, float normalY, float normalZ) { - Axis result = Axis.Y; - float longest = Math.abs(normalY); - float a = Math.abs(normalX); - - if (a > longest) { - result = Axis.X; - longest = a; - } - - return Math.abs(normalZ) > longest - ? Axis.Z : result; - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java deleted file mode 100644 index bf6deebb7..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/NormalHelper.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.helper; - -import net.vulkanmod.render.model.quad.ModelQuadView; -import net.vulkanmod.render.vertex.format.I32_SNorm; -import org.jetbrains.annotations.NotNull; -import org.joml.Vector3f; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; -import net.minecraft.core.Direction; -import net.minecraft.core.Vec3i; -import net.minecraft.util.Mth; - -/** - * Static routines of general utility for renderer implementations. - * Renderers are not required to use these helpers, but they were - * designed to be usable without the default renderer. - */ -public abstract class NormalHelper { - private NormalHelper() { } - - private static final float PACK = 127.0f; - private static final float UNPACK = 1.0f / PACK; - - /** - * Stores a normal plus an extra value as a quartet of signed bytes. - * This is the same normal format that vanilla rendering expects. - * The extra value is for use by shaders. - */ - public static int packNormal(float x, float y, float z, float w) { - x = Mth.clamp(x, -1, 1); - y = Mth.clamp(y, -1, 1); - z = Mth.clamp(z, -1, 1); - w = Mth.clamp(w, -1, 1); - - return ((int) (x * PACK) & 0xFF) | (((int) (y * PACK) & 0xFF) << 8) | (((int) (z * PACK) & 0xFF) << 16) | (((int) (w * PACK) & 0xFF) << 24); - } - - /** - * Version of {@link #packNormal(float, float, float, float)} that accepts a vector type. - */ - public static int packNormal(Vector3f normal, float w) { - return packNormal(normal.x(), normal.y(), normal.z(), w); - } - - /** - * Like {@link #packNormal(float, float, float, float)}, but without a {@code w} value. - */ - public static int packNormal(float x, float y, float z) { - x = Mth.clamp(x, -1, 1); - y = Mth.clamp(y, -1, 1); - z = Mth.clamp(z, -1, 1); - - return ((int) (x * PACK) & 0xFF) | (((int) (y * PACK) & 0xFF) << 8) | (((int) (z * PACK) & 0xFF) << 16); - } - - /** - * Like {@link #packNormal(Vector3f, float)}, but without a {@code w} value. - */ - public static int packNormal(Vector3f normal) { - return packNormal(normal.x(), normal.y(), normal.z()); - } - - public static float unpackNormalX(int packedNormal) { - return ((byte) (packedNormal & 0xFF)) * UNPACK; - } - - public static float unpackNormalY(int packedNormal) { - return ((byte) ((packedNormal >>> 8) & 0xFF)) * UNPACK; - } - - public static float unpackNormalZ(int packedNormal) { - return ((byte) ((packedNormal >>> 16) & 0xFF)) * UNPACK; - } - - public static float unpackNormalW(int packedNormal) { - return ((byte) ((packedNormal >>> 24) & 0xFF)) * UNPACK; - } - - public static void unpackNormal(int packedNormal, Vector3f target) { - target.set(unpackNormalX(packedNormal), unpackNormalY(packedNormal), unpackNormalZ(packedNormal)); - } - - /** - * Computes the face normal of the given quad and saves it in the provided non-null vector. - * If {@link QuadView#nominalFace()} is set will optimize by confirming quad is parallel to that - * face and, if so, use the standard normal for that face direction. - * - *

Will work with triangles also. Assumes counter-clockwise winding order, which is the norm. - * Expects convex quads with all points co-planar. - */ - public static void computeFaceNormal(@NotNull Vector3f saveTo, QuadView q) { - final Direction nominalFace = q.nominalFace(); - - if (nominalFace != null && GeometryHelper.isQuadParallelToFace(nominalFace, q)) { - Vec3i vec = nominalFace.getNormal(); - saveTo.set(vec.getX(), vec.getY(), vec.getZ()); - return; - } - - final float x0 = q.x(0); - final float y0 = q.y(0); - final float z0 = q.z(0); - final float x1 = q.x(1); - final float y1 = q.y(1); - final float z1 = q.z(1); - final float x2 = q.x(2); - final float y2 = q.y(2); - final float z2 = q.z(2); - final float x3 = q.x(3); - final float y3 = q.y(3); - final float z3 = q.z(3); - - final float dx0 = x2 - x0; - final float dy0 = y2 - y0; - final float dz0 = z2 - z0; - final float dx1 = x3 - x1; - final float dy1 = y3 - y1; - final float dz1 = z3 - z1; - - float normX = dy0 * dz1 - dz0 * dy1; - float normY = dz0 * dx1 - dx0 * dz1; - float normZ = dx0 * dy1 - dy0 * dx1; - - float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ); - - if (l != 0) { - normX /= l; - normY /= l; - normZ /= l; - } - - saveTo.set(normX, normY, normZ); - } - - public static int computePackedNormal(ModelQuadView q) { - final float x0 = q.getX(0); - final float y0 = q.getY(0); - final float z0 = q.getZ(0); - final float x1 = q.getX(1); - final float y1 = q.getY(1); - final float z1 = q.getZ(1); - final float x2 = q.getX(2); - final float y2 = q.getY(2); - final float z2 = q.getZ(2); - final float x3 = q.getX(3); - final float y3 = q.getY(3); - final float z3 = q.getZ(3); - - final float dx0 = x2 - x0; - final float dy0 = y2 - y0; - final float dz0 = z2 - z0; - final float dx1 = x3 - x1; - final float dy1 = y3 - y1; - final float dz1 = z3 - z1; - - float normX = dy0 * dz1 - dz0 * dy1; - float normY = dz0 * dx1 - dx0 * dz1; - float normZ = dx0 * dy1 - dy0 * dx1; - - float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ); - - if (l != 0) { - normX /= l; - normY /= l; - normZ /= l; - } - - return I32_SNorm.packNormal(normX, normY, normZ); - } - - public static int packedNormalFromDirection(Direction direction) { - Vec3i normal = direction.getNormal(); - - return I32_SNorm.packNormal(normal.getX(), normal.getY(), normal.getZ()); - } - - public static void unpackNormalTo(int packedNormal, Vector3f normal) { - normal.set(I32_SNorm.unpackX(packedNormal), I32_SNorm.unpackY(packedNormal), I32_SNorm.unpackZ(packedNormal)); - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/TextureHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/TextureHelper.java deleted file mode 100644 index bc622cd92..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/helper/TextureHelper.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.helper; - -import net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.core.Direction; - -/** - * Handles most texture-baking use cases for model loaders and model libraries - * via {@link #bakeSprite(MutableQuadView, TextureAtlasSprite, int)}. Also used by the API - * itself to implement automatic block-breaking models for enhanced models. - */ -public class TextureHelper { - private TextureHelper() { } - - private static final float NORMALIZER = 1f / 16f; - - /** - * Bakes textures in the provided vertex data, handling UV locking, - * rotation, interpolation, etc. Textures must not be already baked. - */ - public static void bakeSprite(MutableQuadView quad, TextureAtlasSprite sprite, int bakeFlags) { - if (quad.nominalFace() != null && (MutableQuadView.BAKE_LOCK_UV & bakeFlags) != 0) { - // Assigns normalized UV coordinates based on vertex positions - applyModifier(quad, UVLOCKERS[quad.nominalFace().get3DDataValue()]); - } else if ((MutableQuadView.BAKE_NORMALIZED & bakeFlags) == 0) { // flag is NOT set, UVs are assumed to not be normalized yet as is the default, normalize through dividing by 16 - // Scales from 0-16 to 0-1 - applyModifier(quad, (q, i) -> q.uv(i, q.u(i) * NORMALIZER, q.v(i) * NORMALIZER)); - } - - final int rotation = bakeFlags & 3; - - if (rotation != 0) { - // Rotates texture around the center of sprite. - // Assumes normalized coordinates. - applyModifier(quad, ROTATIONS[rotation]); - } - - if ((MutableQuadView.BAKE_FLIP_U & bakeFlags) != 0) { - // Inverts U coordinates. Assumes normalized (0-1) values. - applyModifier(quad, (q, i) -> q.uv(i, 1 - q.u(i), q.v(i))); - } - - if ((MutableQuadView.BAKE_FLIP_V & bakeFlags) != 0) { - // Inverts V coordinates. Assumes normalized (0-1) values. - applyModifier(quad, (q, i) -> q.uv(i, q.u(i), 1 - q.v(i))); - } - - interpolate(quad, sprite); - } - - /** - * Faster than sprite method. Sprite computes span and normalizes inputs each call, - * so we'd have to denormalize before we called, only to have the sprite renormalize immediately. - */ - private static void interpolate(MutableQuadView q, TextureAtlasSprite sprite) { - final float uMin = sprite.getU0(); - final float uSpan = sprite.getU1() - uMin; - final float vMin = sprite.getV0(); - final float vSpan = sprite.getV1() - vMin; - - for (int i = 0; i < 4; i++) { - q.uv(i, uMin + q.u(i) * uSpan, vMin + q.v(i) * vSpan); - } - } - - @FunctionalInterface - private interface VertexModifier { - void apply(MutableQuadView quad, int vertexIndex); - } - - private static void applyModifier(MutableQuadView quad, VertexModifier modifier) { - for (int i = 0; i < 4; i++) { - modifier.apply(quad, i); - } - } - - private static final VertexModifier[] ROTATIONS = new VertexModifier[] { - null, - (q, i) -> q.uv(i, q.v(i), 1 - q.u(i)), //90 - (q, i) -> q.uv(i, 1 - q.u(i), 1 - q.v(i)), //180 - (q, i) -> q.uv(i, 1 - q.v(i), q.u(i)) // 270 - }; - - private static final VertexModifier[] UVLOCKERS = new VertexModifier[6]; - - static { - UVLOCKERS[Direction.EAST.get3DDataValue()] = (q, i) -> q.uv(i, 1 - q.z(i), 1 - q.y(i)); - UVLOCKERS[Direction.WEST.get3DDataValue()] = (q, i) -> q.uv(i, q.z(i), 1 - q.y(i)); - UVLOCKERS[Direction.NORTH.get3DDataValue()] = (q, i) -> q.uv(i, 1 - q.x(i), 1 - q.y(i)); - UVLOCKERS[Direction.SOUTH.get3DDataValue()] = (q, i) -> q.uv(i, q.x(i), 1 - q.y(i)); - UVLOCKERS[Direction.DOWN.get3DDataValue()] = (q, i) -> q.uv(i, q.x(i), 1 - q.z(i)); - UVLOCKERS[Direction.UP.get3DDataValue()] = (q, i) -> q.uv(i, q.x(i), q.z(i)); - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java deleted file mode 100644 index 91b510452..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialFinderImpl.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.material; - -import java.util.Objects; - -import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; -import net.fabricmc.fabric.api.renderer.v1.material.MaterialFinder; -import net.fabricmc.fabric.api.renderer.v1.material.MaterialView; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; -import net.fabricmc.fabric.api.util.TriState; - -public class MaterialFinderImpl extends MaterialViewImpl implements MaterialFinder { - private static int defaultBits = 0; - - static { - MaterialFinderImpl finder = new MaterialFinderImpl(); - finder.ambientOcclusion(TriState.DEFAULT); - finder.glint(TriState.DEFAULT); - defaultBits = finder.bits; - - if (!areBitsValid(defaultBits)) { - throw new AssertionError("Default MaterialFinder bits are not valid!"); - } - } - - public MaterialFinderImpl() { - super(defaultBits); - } - - @Override - public MaterialFinder blendMode(BlendMode blendMode) { - Objects.requireNonNull(blendMode, "BlendMode may not be null"); - - bits = (bits & ~BLEND_MODE_MASK) | (blendMode.ordinal() << BLEND_MODE_BIT_OFFSET); - return this; - } - - @Override - public MaterialFinder disableColorIndex(boolean disable) { - bits = disable ? (bits | COLOR_DISABLE_FLAG) : (bits & ~COLOR_DISABLE_FLAG); - return this; - } - - @Override - public MaterialFinder emissive(boolean isEmissive) { - bits = isEmissive ? (bits | EMISSIVE_FLAG) : (bits & ~EMISSIVE_FLAG); - return this; - } - - @Override - public MaterialFinder disableDiffuse(boolean disable) { - bits = disable ? (bits | DIFFUSE_FLAG) : (bits & ~DIFFUSE_FLAG); - return this; - } - - @Override - public MaterialFinder ambientOcclusion(TriState mode) { - Objects.requireNonNull(mode, "ambient occlusion TriState may not be null"); - - bits = (bits & ~AO_MASK) | (mode.ordinal() << AO_BIT_OFFSET); - return this; - } - - @Override - public MaterialFinder glint(TriState mode) { - Objects.requireNonNull(mode, "glint TriState may not be null"); - - bits = (bits & ~GLINT_MASK) | (mode.ordinal() << GLINT_BIT_OFFSET); - return this; - } - - @Override - public MaterialFinder shadeMode(ShadeMode mode) { - Objects.requireNonNull(mode, "ShadeMode may not be null"); - - bits = (bits & ~SHADE_MODE_MASK) | (mode.ordinal() << SHADE_MODE_BIT_OFFSET); - return this; - } - - @Override - public MaterialFinder copyFrom(MaterialView material) { - bits = ((MaterialViewImpl) material).bits; - return this; - } - - @Override - public MaterialFinder clear() { - bits = defaultBits; - return this; - } - - @Override - public RenderMaterial find() { - return RenderMaterialImpl.byIndex(bits); - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java deleted file mode 100644 index 0ae070574..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/MaterialViewImpl.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.material; - -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.bitMask; - -import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; -import net.fabricmc.fabric.api.renderer.v1.material.MaterialView; -import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; -import net.fabricmc.fabric.api.util.TriState; -import net.minecraft.util.Mth; - -/** - * Default implementation of the standard render materials. - * The underlying representation is simply an int with bit-wise - * packing of the various material properties. This offers - * easy/fast interning via int/object hashmap. - */ -public class MaterialViewImpl implements MaterialView { - private static final BlendMode[] BLEND_MODES = BlendMode.values(); - private static final int BLEND_MODE_COUNT = BLEND_MODES.length; - private static final TriState[] TRI_STATES = TriState.values(); - private static final int TRI_STATE_COUNT = TRI_STATES.length; - private static final ShadeMode[] SHADE_MODES = ShadeMode.values(); - private static final int SHADE_MODE_COUNT = SHADE_MODES.length; - - protected static final int BLEND_MODE_BIT_LENGTH = Mth.ceillog2(BLEND_MODE_COUNT); - protected static final int COLOR_DISABLE_BIT_LENGTH = 1; - protected static final int EMISSIVE_BIT_LENGTH = 1; - protected static final int DIFFUSE_BIT_LENGTH = 1; - protected static final int AO_BIT_LENGTH = Mth.ceillog2(TRI_STATE_COUNT); - protected static final int GLINT_BIT_LENGTH = Mth.ceillog2(TRI_STATE_COUNT); - protected static final int SHADE_MODE_BIT_LENGTH = Mth.ceillog2(SHADE_MODE_COUNT); - - protected static final int BLEND_MODE_BIT_OFFSET = 0; - protected static final int COLOR_DISABLE_BIT_OFFSET = BLEND_MODE_BIT_OFFSET + BLEND_MODE_BIT_LENGTH; - protected static final int EMISSIVE_BIT_OFFSET = COLOR_DISABLE_BIT_OFFSET + COLOR_DISABLE_BIT_LENGTH; - protected static final int DIFFUSE_BIT_OFFSET = EMISSIVE_BIT_OFFSET + EMISSIVE_BIT_LENGTH; - protected static final int AO_BIT_OFFSET = DIFFUSE_BIT_OFFSET + DIFFUSE_BIT_LENGTH; - protected static final int GLINT_BIT_OFFSET = AO_BIT_OFFSET + AO_BIT_LENGTH; - protected static final int SHADE_MODE_BIT_OFFSET = GLINT_BIT_OFFSET + GLINT_BIT_LENGTH; - public static final int TOTAL_BIT_LENGTH = SHADE_MODE_BIT_OFFSET + SHADE_MODE_BIT_LENGTH; - - protected static final int BLEND_MODE_MASK = bitMask(BLEND_MODE_BIT_LENGTH, BLEND_MODE_BIT_OFFSET); - protected static final int COLOR_DISABLE_FLAG = bitMask(COLOR_DISABLE_BIT_LENGTH, COLOR_DISABLE_BIT_OFFSET); - protected static final int EMISSIVE_FLAG = bitMask(EMISSIVE_BIT_LENGTH, EMISSIVE_BIT_OFFSET); - protected static final int DIFFUSE_FLAG = bitMask(DIFFUSE_BIT_LENGTH, DIFFUSE_BIT_OFFSET); - protected static final int AO_MASK = bitMask(AO_BIT_LENGTH, AO_BIT_OFFSET); - protected static final int GLINT_MASK = bitMask(GLINT_BIT_LENGTH, GLINT_BIT_OFFSET); - protected static final int SHADE_MODE_MASK = bitMask(SHADE_MODE_BIT_LENGTH, SHADE_MODE_BIT_OFFSET); - - protected static boolean areBitsValid(int bits) { - int blendMode = (bits & BLEND_MODE_MASK) >>> BLEND_MODE_BIT_OFFSET; - int ao = (bits & AO_MASK) >>> AO_BIT_OFFSET; - int glint = (bits & GLINT_MASK) >>> GLINT_BIT_OFFSET; - int shadeMode = (bits & SHADE_MODE_MASK) >>> SHADE_MODE_BIT_OFFSET; - - return blendMode < BLEND_MODE_COUNT - && ao < TRI_STATE_COUNT - && glint < TRI_STATE_COUNT - && shadeMode < SHADE_MODE_COUNT; - } - - protected int bits; - - protected MaterialViewImpl(int bits) { - this.bits = bits; - } - - @Override - public BlendMode blendMode() { - return BLEND_MODES[(bits & BLEND_MODE_MASK) >>> BLEND_MODE_BIT_OFFSET]; - } - - @Override - public boolean disableColorIndex() { - return (bits & COLOR_DISABLE_FLAG) != 0; - } - - @Override - public boolean emissive() { - return (bits & EMISSIVE_FLAG) != 0; - } - - @Override - public boolean disableDiffuse() { - return (bits & DIFFUSE_FLAG) != 0; - } - - @Override - public TriState ambientOcclusion() { - return TRI_STATES[(bits & AO_MASK) >>> AO_BIT_OFFSET]; - } - - @Override - public TriState glint() { - return TRI_STATES[(bits & GLINT_MASK) >>> GLINT_BIT_OFFSET]; - } - - @Override - public ShadeMode shadeMode() { - return SHADE_MODES[(bits & SHADE_MODE_MASK) >>> SHADE_MODE_BIT_OFFSET]; - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/RenderMaterialImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/RenderMaterialImpl.java deleted file mode 100644 index 17e4602bb..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/material/RenderMaterialImpl.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.material; - -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; - -public class RenderMaterialImpl extends MaterialViewImpl implements RenderMaterial { - public static final int VALUE_COUNT = 1 << TOTAL_BIT_LENGTH; - private static final RenderMaterialImpl[] BY_INDEX = new RenderMaterialImpl[VALUE_COUNT]; - - static { - for (int i = 0; i < VALUE_COUNT; i++) { - if (areBitsValid(i)) { - BY_INDEX[i] = new RenderMaterialImpl(i); - } - } - } - - private RenderMaterialImpl(int bits) { - super(bits); - } - - public int index() { - return bits; - } - - public static RenderMaterialImpl byIndex(int index) { - return BY_INDEX[index]; - } - - public static RenderMaterialImpl setDisableDiffuse(RenderMaterialImpl material, boolean disable) { - if (material.disableDiffuse() != disable) { - return byIndex(disable ? (material.bits | DIFFUSE_FLAG) : (material.bits & ~DIFFUSE_FLAG)); - } - - return material; - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java deleted file mode 100644 index f1cf763cc..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/EncodingFormat.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.mesh; - -import com.google.common.base.Preconditions; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; -import org.jetbrains.annotations.Nullable; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; -import net.fabricmc.fabric.api.renderer.v1.model.ModelHelper; -import net.vulkanmod.render.chunk.build.frapi.helper.GeometryHelper; -import net.vulkanmod.render.chunk.build.frapi.material.MaterialViewImpl; -import net.vulkanmod.render.chunk.build.frapi.material.RenderMaterialImpl; -import net.minecraft.core.Direction; -import net.minecraft.util.Mth; - -/** - * Holds all the array offsets and bit-wise encoders/decoders for - * packing/unpacking quad data in an array of integers. - * All of this is implementation-specific - that's why it isn't a "helper" class. - */ -public abstract class EncodingFormat { - private EncodingFormat() { } - - static final int HEADER_BITS = 0; - static final int HEADER_FACE_NORMAL = 1; - static final int HEADER_COLOR_INDEX = 2; - static final int HEADER_TAG = 3; - public static final int HEADER_STRIDE = 4; - - static final int VERTEX_X; - static final int VERTEX_Y; - static final int VERTEX_Z; - static final int VERTEX_COLOR; - static final int VERTEX_U; - static final int VERTEX_V; - static final int VERTEX_LIGHTMAP; - static final int VERTEX_NORMAL; - public static final int VERTEX_STRIDE; - - public static final int QUAD_STRIDE; - public static final int QUAD_STRIDE_BYTES; - public static final int TOTAL_STRIDE; - - static { - final VertexFormat format = DefaultVertexFormat.BLOCK; - VERTEX_X = HEADER_STRIDE + 0; - VERTEX_Y = HEADER_STRIDE + 1; - VERTEX_Z = HEADER_STRIDE + 2; - VERTEX_COLOR = HEADER_STRIDE + 3; - VERTEX_U = HEADER_STRIDE + 4; - VERTEX_V = VERTEX_U + 1; - VERTEX_LIGHTMAP = HEADER_STRIDE + 6; - VERTEX_NORMAL = HEADER_STRIDE + 7; - VERTEX_STRIDE = format.getVertexSize() / 4; - QUAD_STRIDE = VERTEX_STRIDE * 4; - QUAD_STRIDE_BYTES = QUAD_STRIDE * 4; - TOTAL_STRIDE = HEADER_STRIDE + QUAD_STRIDE; - - Preconditions.checkState(VERTEX_STRIDE == QuadView.VANILLA_VERTEX_STRIDE, "Indigo vertex stride (%s) mismatched with rendering API (%s)", VERTEX_STRIDE, QuadView.VANILLA_VERTEX_STRIDE); - Preconditions.checkState(QUAD_STRIDE == QuadView.VANILLA_QUAD_STRIDE, "Indigo quad stride (%s) mismatched with rendering API (%s)", QUAD_STRIDE, QuadView.VANILLA_QUAD_STRIDE); - } - - /** used for quick clearing of quad buffers. */ - static final int[] EMPTY = new int[TOTAL_STRIDE]; - - private static final int DIRECTION_COUNT = Direction.values().length; - private static final int NULLABLE_DIRECTION_COUNT = DIRECTION_COUNT + 1; - - private static final int CULL_BIT_LENGTH = Mth.ceillog2(NULLABLE_DIRECTION_COUNT); - private static final int LIGHT_BIT_LENGTH = Mth.ceillog2(DIRECTION_COUNT); - private static final int NORMALS_BIT_LENGTH = 4; - private static final int GEOMETRY_BIT_LENGTH = GeometryHelper.FLAG_BIT_COUNT; - private static final int MATERIAL_BIT_LENGTH = MaterialViewImpl.TOTAL_BIT_LENGTH; - - private static final int CULL_BIT_OFFSET = 0; - private static final int LIGHT_BIT_OFFSET = CULL_BIT_OFFSET + CULL_BIT_LENGTH; - private static final int NORMALS_BIT_OFFSET = LIGHT_BIT_OFFSET + LIGHT_BIT_LENGTH; - private static final int GEOMETRY_BIT_OFFSET = NORMALS_BIT_OFFSET + NORMALS_BIT_LENGTH; - private static final int MATERIAL_BIT_OFFSET = GEOMETRY_BIT_OFFSET + GEOMETRY_BIT_LENGTH; - private static final int TOTAL_BIT_LENGTH = MATERIAL_BIT_OFFSET + MATERIAL_BIT_LENGTH; - - private static final int CULL_MASK = bitMask(CULL_BIT_LENGTH, CULL_BIT_OFFSET); - private static final int LIGHT_MASK = bitMask(LIGHT_BIT_LENGTH, LIGHT_BIT_OFFSET); - private static final int NORMALS_MASK = bitMask(NORMALS_BIT_LENGTH, NORMALS_BIT_OFFSET); - private static final int GEOMETRY_MASK = bitMask(GEOMETRY_BIT_LENGTH, GEOMETRY_BIT_OFFSET); - private static final int MATERIAL_MASK = bitMask(MATERIAL_BIT_LENGTH, MATERIAL_BIT_OFFSET); - - static { - Preconditions.checkArgument(TOTAL_BIT_LENGTH <= 32, "Indigo header encoding bit count (%s) exceeds integer bit length)", TOTAL_STRIDE); - } - - public static int bitMask(int bitLength, int bitOffset) { - return ((1 << bitLength) - 1) << bitOffset; - } - - @Nullable - static Direction cullFace(int bits) { - return ModelHelper.faceFromIndex((bits & CULL_MASK) >>> CULL_BIT_OFFSET); - } - - static int cullFace(int bits, @Nullable Direction face) { - return (bits & ~CULL_MASK) | (ModelHelper.toFaceIndex(face) << CULL_BIT_OFFSET); - } - - static Direction lightFace(int bits) { - return ModelHelper.faceFromIndex((bits & LIGHT_MASK) >>> LIGHT_BIT_OFFSET); - } - - static int lightFace(int bits, Direction face) { - return (bits & ~LIGHT_MASK) | (ModelHelper.toFaceIndex(face) << LIGHT_BIT_OFFSET); - } - - /** indicate if vertex normal has been set - bits correspond to vertex ordinals. */ - static int normalFlags(int bits) { - return (bits & NORMALS_MASK) >>> NORMALS_BIT_OFFSET; - } - - static int normalFlags(int bits, int normalFlags) { - return (bits & ~NORMALS_MASK) | ((normalFlags << NORMALS_BIT_OFFSET) & NORMALS_MASK); - } - - static int geometryFlags(int bits) { - return (bits & GEOMETRY_MASK) >>> GEOMETRY_BIT_OFFSET; - } - - static int geometryFlags(int bits, int geometryFlags) { - return (bits & ~GEOMETRY_MASK) | ((geometryFlags << GEOMETRY_BIT_OFFSET) & GEOMETRY_MASK); - } - - static RenderMaterialImpl material(int bits) { - return RenderMaterialImpl.byIndex((bits & MATERIAL_MASK) >>> MATERIAL_BIT_OFFSET); - } - - static int material(int bits, RenderMaterialImpl material) { - return (bits & ~MATERIAL_MASK) | (material.index() << MATERIAL_BIT_OFFSET); - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshBuilderImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshBuilderImpl.java deleted file mode 100644 index b5119de51..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshBuilderImpl.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.mesh; - -import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh; -import net.fabricmc.fabric.api.renderer.v1.mesh.MeshBuilder; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; - -/** - * Our implementation of {@link MeshBuilder}, used for static mesh creation and baking. - * Not much to it - mainly it just needs to grow the int[] array as quads are appended - * and maintain/provide a properly-configured {@link net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView} instance. - * All the encoding and other work is handled in the quad base classes. - * The one interesting bit is in {@link Maker#emitDirectly()}. - */ -public class MeshBuilderImpl implements MeshBuilder { - private int[] data = new int[256]; - private int index = 0; - private int limit = data.length; - private final Maker maker = new Maker(); - - public MeshBuilderImpl() { - ensureCapacity(EncodingFormat.TOTAL_STRIDE); - maker.data = data; - maker.baseIndex = index; - maker.clear(); - } - - protected void ensureCapacity(int stride) { - if (stride > limit - index) { - limit *= 2; - final int[] bigger = new int[limit]; - System.arraycopy(data, 0, bigger, 0, index); - data = bigger; - maker.data = data; - } - } - - @Override - public QuadEmitter getEmitter() { - maker.clear(); - return maker; - } - - @Override - public Mesh build() { - final int[] packed = new int[index]; - System.arraycopy(data, 0, packed, 0, index); - index = 0; - maker.baseIndex = index; - maker.clear(); - return new MeshImpl(packed); - } - - /** - * Our base classes are used differently so we define final - * encoding steps in subtypes. This will be a static mesh used - * at render time so we want to capture all geometry now and - * apply non-location-dependent lighting. - */ - private class Maker extends MutableQuadViewImpl { - @Override - public void emitDirectly() { - computeGeometry(); - index += EncodingFormat.TOTAL_STRIDE; - ensureCapacity(EncodingFormat.TOTAL_STRIDE); - baseIndex = index; - } - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshImpl.java deleted file mode 100644 index ff23f44f7..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MeshImpl.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.mesh; - -import java.util.function.Consumer; - -import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; - -/** - * Implementation of {@link Mesh}. - * The way we encode meshes makes it very simple. - */ -public class MeshImpl implements Mesh { - /** Used to satisfy external calls to {@link #forEach(Consumer)}. */ - private final ThreadLocal cursorPool = ThreadLocal.withInitial(QuadViewImpl::new); - - final int[] data; - - MeshImpl(int[] data) { - this.data = data; - } - - @Override - public void forEach(Consumer consumer) { - forEach(consumer, cursorPool.get()); - } - - /** - * The renderer can call this with its own cursor - * to avoid the performance hit of a thread-local lookup. - * Also means renderer can hold final references to quad buffers. - */ - void forEach(Consumer consumer, QuadViewImpl cursor) { - final int limit = data.length; - int index = 0; - cursor.data = this.data; - - while (index < limit) { - cursor.baseIndex = index; - cursor.load(); - consumer.accept(cursor); - index += EncodingFormat.TOTAL_STRIDE; - } - } - - @Override - public void outputTo(QuadEmitter emitter) { - MutableQuadViewImpl e = (MutableQuadViewImpl) emitter; - final int[] data = this.data; - final int limit = data.length; - int index = 0; - - while (index < limit) { - System.arraycopy(data, index, e.data, e.baseIndex, EncodingFormat.TOTAL_STRIDE); - e.load(); - e.emitDirectly(); - index += EncodingFormat.TOTAL_STRIDE; - } - - e.clear(); - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java deleted file mode 100644 index 3b3fb644e..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/MutableQuadViewImpl.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.mesh; - -import net.vulkanmod.render.chunk.build.frapi.VulkanModRenderer; -import net.vulkanmod.render.model.quad.ModelQuadView; -import org.jetbrains.annotations.Nullable; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; -import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; -import net.vulkanmod.render.chunk.build.frapi.helper.NormalHelper; -import net.vulkanmod.render.chunk.build.frapi.helper.TextureHelper; -import net.vulkanmod.render.chunk.build.frapi.material.RenderMaterialImpl; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.core.Direction; - -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.*; - -/** - * Almost-concrete implementation of a mutable quad. The only missing part is {@link #emitDirectly()}, - * because that depends on where/how it is used. (Mesh encoding vs. render-time transformation). - * - *

In many cases an instance of this class is used as an "editor quad". The editor quad's - * {@link #emitDirectly()} method calls some other internal method that transforms the quad - * data and then buffers it. Transformations should be the same as they would be in a vanilla - * render - the editor is serving mainly as a way to access vertex data without magical - * numbers. It also allows for a consistent interface for those transformations. - */ -public abstract class MutableQuadViewImpl extends QuadViewImpl implements QuadEmitter { - public void clear() { - System.arraycopy(EMPTY, 0, data, baseIndex, EncodingFormat.TOTAL_STRIDE); - isGeometryInvalid = true; - nominalFace = null; - normalFlags(0); - tag(0); - colorIndex(-1); - cullFace(null); - material(VulkanModRenderer.MATERIAL_STANDARD); - } - - @Override - public MutableQuadViewImpl pos(int vertexIndex, float x, float y, float z) { - final int index = baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_X; - data[index] = Float.floatToRawIntBits(x); - data[index + 1] = Float.floatToRawIntBits(y); - data[index + 2] = Float.floatToRawIntBits(z); - isGeometryInvalid = true; - return this; - } - - @Override - public MutableQuadViewImpl color(int vertexIndex, int color) { - data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_COLOR] = color; - return this; - } - - @Override - public MutableQuadViewImpl uv(int vertexIndex, float u, float v) { - final int i = baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_U; - data[i] = Float.floatToRawIntBits(u); - data[i + 1] = Float.floatToRawIntBits(v); - return this; - } - - @Override - public MutableQuadViewImpl spriteBake(TextureAtlasSprite sprite, int bakeFlags) { - TextureHelper.bakeSprite(this, sprite, bakeFlags); - return this; - } - - @Override - public MutableQuadViewImpl lightmap(int vertexIndex, int lightmap) { - data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_LIGHTMAP] = lightmap; - return this; - } - - protected void normalFlags(int flags) { - data[baseIndex + HEADER_BITS] = EncodingFormat.normalFlags(data[baseIndex + HEADER_BITS], flags); - } - - @Override - public MutableQuadViewImpl normal(int vertexIndex, float x, float y, float z) { - normalFlags(normalFlags() | (1 << vertexIndex)); - data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_NORMAL] = NormalHelper.packNormal(x, y, z); - return this; - } - - /** - * Internal helper method. Copies face normals to vertex normals lacking one. - */ - public final void populateMissingNormals() { - final int normalFlags = this.normalFlags(); - - if (normalFlags == 0b1111) return; - - final int packedFaceNormal = packedFaceNormal(); - - for (int v = 0; v < 4; v++) { - if ((normalFlags & (1 << v)) == 0) { - data[baseIndex + v * VERTEX_STRIDE + VERTEX_NORMAL] = packedFaceNormal; - } - } - - normalFlags(0b1111); - } - - @Override - public final MutableQuadViewImpl cullFace(@Nullable Direction face) { - data[baseIndex + HEADER_BITS] = EncodingFormat.cullFace(data[baseIndex + HEADER_BITS], face); - nominalFace(face); - return this; - } - - @Override - public final MutableQuadViewImpl nominalFace(@Nullable Direction face) { - nominalFace = face; - return this; - } - - @Override - public final MutableQuadViewImpl material(RenderMaterial material) { - if (material == null) { - material = VulkanModRenderer.MATERIAL_STANDARD; - } - - data[baseIndex + HEADER_BITS] = EncodingFormat.material(data[baseIndex + HEADER_BITS], (RenderMaterialImpl) material); - return this; - } - - @Override - public final MutableQuadViewImpl colorIndex(int colorIndex) { - data[baseIndex + HEADER_COLOR_INDEX] = colorIndex; - return this; - } - - @Override - public final MutableQuadViewImpl tag(int tag) { - data[baseIndex + HEADER_TAG] = tag; - return this; - } - - @Override - public MutableQuadViewImpl copyFrom(QuadView quad) { - final QuadViewImpl q = (QuadViewImpl) quad; - q.computeGeometry(); - - System.arraycopy(q.data, q.baseIndex, data, baseIndex, EncodingFormat.TOTAL_STRIDE); - faceNormal.set(q.faceNormal); - nominalFace = q.nominalFace; - isGeometryInvalid = false; - return this; - } - - @Override - public final MutableQuadViewImpl fromVanilla(int[] quadData, int startIndex) { - System.arraycopy(quadData, startIndex, data, baseIndex + HEADER_STRIDE, VANILLA_QUAD_STRIDE); - isGeometryInvalid = true; - - int colorIndex = baseIndex + VERTEX_COLOR; - - for (int i = 0; i < 4; i++) { - data[colorIndex] = ColorHelper.fromVanillaColor(data[colorIndex]); - colorIndex += VERTEX_STRIDE; - } - - return this; - } - - @Override - public final MutableQuadViewImpl fromVanilla(BakedQuad quad, RenderMaterial material, @Nullable Direction cullFace) { - fromVanilla(quad.getVertices(), 0); - data[baseIndex + HEADER_BITS] = EncodingFormat.cullFace(0, cullFace); - nominalFace(quad.getDirection()); - colorIndex(quad.getTintIndex()); - - if (!quad.isShade()) { - material = RenderMaterialImpl.setDisableDiffuse((RenderMaterialImpl) material, true); - } - - material(material); - tag(0); - - // Copy data from BakedQuad instead of calculating properties - ModelQuadView quadView = (ModelQuadView) quad; - int normal = quadView.getNormal(); - data[baseIndex + HEADER_FACE_NORMAL] = normal; - NormalHelper.unpackNormalTo(normal, faceNormal); - - Direction lightFace = quadView.lightFace(); - data[baseIndex + HEADER_BITS] = EncodingFormat.lightFace(data[baseIndex + HEADER_BITS], lightFace); - data[baseIndex + HEADER_BITS] = EncodingFormat.geometryFlags(data[baseIndex + HEADER_BITS], quadView.getFlags()); - - this.facing = quadView.getQuadFacing(); - - this.isGeometryInvalid = false; - return this; - } - - /** - * Emit the quad without clearing the underlying data. - * Geometry is not guaranteed to be valid when called, but can be computed by calling {@link #computeGeometry()}. - */ - public abstract void emitDirectly(); - - @Override - public final MutableQuadViewImpl emit() { - emitDirectly(); - clear(); - return this; - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java deleted file mode 100644 index 526e45b61..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/mesh/QuadViewImpl.java +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.mesh; - -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_BITS; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_COLOR_INDEX; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_FACE_NORMAL; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_STRIDE; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.HEADER_TAG; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.QUAD_STRIDE; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_COLOR; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_LIGHTMAP; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_NORMAL; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_STRIDE; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_U; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_V; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_X; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_Y; -import static net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat.VERTEX_Z; - -import net.vulkanmod.render.chunk.cull.QuadFacing; -import net.vulkanmod.render.model.quad.ModelQuadFlags; -import net.vulkanmod.render.model.quad.ModelQuadView; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.joml.Vector2f; -import org.joml.Vector3f; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; -import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; -import net.vulkanmod.render.chunk.build.frapi.helper.GeometryHelper; -import net.vulkanmod.render.chunk.build.frapi.helper.NormalHelper; -import net.vulkanmod.render.chunk.build.frapi.material.RenderMaterialImpl; -import net.minecraft.core.Direction; - -/** - * Base class for all quads / quad makers. Handles the ugly bits - * of maintaining and encoding the quad state. - */ -public class QuadViewImpl implements QuadView, ModelQuadView { - @Nullable - protected Direction nominalFace; - /** True when face normal, light face, or geometry flags may not match geometry. */ - protected boolean isGeometryInvalid = true; - protected final Vector3f faceNormal = new Vector3f(); - - /** Size and where it comes from will vary in subtypes. But in all cases quad is fully encoded to array. */ - protected int[] data; - - /** Beginning of the quad. Also the header index. */ - protected int baseIndex = 0; - - protected QuadFacing facing; - - /** - * Decodes necessary state from the backing data array. - * The encoded data must contain valid computed geometry. - */ - public void load() { - isGeometryInvalid = false; - nominalFace = lightFace(); - NormalHelper.unpackNormal(packedFaceNormal(), faceNormal); - facing = QuadFacing.fromNormal(faceNormal); - } - - protected void computeGeometry() { - if (isGeometryInvalid) { - isGeometryInvalid = false; - - NormalHelper.computeFaceNormal(faceNormal, this); - data[baseIndex + HEADER_FACE_NORMAL] = NormalHelper.packNormal(faceNormal); - - // depends on face normal - Direction lightFace = GeometryHelper.lightFace(this); - data[baseIndex + HEADER_BITS] = EncodingFormat.lightFace(data[baseIndex + HEADER_BITS], lightFace); - - // depends on light face - data[baseIndex + HEADER_BITS] = EncodingFormat.geometryFlags(data[baseIndex + HEADER_BITS], ModelQuadFlags.getQuadFlags(this, lightFace)); - - facing = QuadFacing.fromNormal(faceNormal); - } - } - - /** gets flags used for lighting - lazily computed via {@link GeometryHelper#computeShapeFlags(QuadView)}. */ - public int geometryFlags() { - computeGeometry(); - return EncodingFormat.geometryFlags(data[baseIndex + HEADER_BITS]); - } - - public boolean hasShade() { - return !material().disableDiffuse(); - } - - @Override - public float x(int vertexIndex) { - return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_X]); - } - - @Override - public float y(int vertexIndex) { - return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_Y]); - } - - @Override - public float z(int vertexIndex) { - return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_Z]); - } - - @Override - public float posByIndex(int vertexIndex, int coordinateIndex) { - return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_X + coordinateIndex]); - } - - @Override - public Vector3f copyPos(int vertexIndex, @Nullable Vector3f target) { - if (target == null) { - target = new Vector3f(); - } - - final int index = baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_X; - target.set(Float.intBitsToFloat(data[index]), Float.intBitsToFloat(data[index + 1]), Float.intBitsToFloat(data[index + 2])); - return target; - } - - @Override - public int color(int vertexIndex) { - return data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_COLOR]; - } - - @Override - public float u(int vertexIndex) { - return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_U]); - } - - @Override - public float v(int vertexIndex) { - return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_V]); - } - - @Override - public Vector2f copyUv(int vertexIndex, @Nullable Vector2f target) { - if (target == null) { - target = new Vector2f(); - } - - final int index = baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_U; - target.set(Float.intBitsToFloat(data[index]), Float.intBitsToFloat(data[index + 1])); - return target; - } - - @Override - public int lightmap(int vertexIndex) { - return data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_LIGHTMAP]; - } - - public int normalFlags() { - return EncodingFormat.normalFlags(data[baseIndex + HEADER_BITS]); - } - - @Override - public boolean hasNormal(int vertexIndex) { - return (normalFlags() & (1 << vertexIndex)) != 0; - } - - /** True if any vertex normal has been set. */ - public boolean hasVertexNormals() { - return normalFlags() != 0; - } - - /** True if all vertex normals have been set. */ - public boolean hasAllVertexNormals() { - return (normalFlags() & 0b1111) == 0b1111; - } - - protected final int normalIndex(int vertexIndex) { - return baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_NORMAL; - } - - @Override - public float normalX(int vertexIndex) { - return hasNormal(vertexIndex) ? NormalHelper.unpackNormalX(data[normalIndex(vertexIndex)]) : Float.NaN; - } - - @Override - public float normalY(int vertexIndex) { - return hasNormal(vertexIndex) ? NormalHelper.unpackNormalY(data[normalIndex(vertexIndex)]) : Float.NaN; - } - - @Override - public float normalZ(int vertexIndex) { - return hasNormal(vertexIndex) ? NormalHelper.unpackNormalZ(data[normalIndex(vertexIndex)]) : Float.NaN; - } - - @Override - @Nullable - public Vector3f copyNormal(int vertexIndex, @Nullable Vector3f target) { - if (hasNormal(vertexIndex)) { - if (target == null) { - target = new Vector3f(); - } - - final int normal = data[normalIndex(vertexIndex)]; - NormalHelper.unpackNormal(normal, target); - return target; - } else { - return null; - } - } - - @Override - @Nullable - public final Direction cullFace() { - return EncodingFormat.cullFace(data[baseIndex + HEADER_BITS]); - } - - @Override - @NotNull - public final Direction lightFace() { - computeGeometry(); - return EncodingFormat.lightFace(data[baseIndex + HEADER_BITS]); - } - - @Override - @Nullable - public final Direction nominalFace() { - return nominalFace; - } - - public final int packedFaceNormal() { - computeGeometry(); - return data[baseIndex + HEADER_FACE_NORMAL]; - } - - @Override - public final Vector3f faceNormal() { - computeGeometry(); - return faceNormal; - } - - @Override - public final RenderMaterialImpl material() { - return EncodingFormat.material(data[baseIndex + HEADER_BITS]); - } - - @Override - public final int colorIndex() { - return data[baseIndex + HEADER_COLOR_INDEX]; - } - - @Override - public final int tag() { - return data[baseIndex + HEADER_TAG]; - } - - @Override - public final void toVanilla(int[] target, int targetIndex) { - System.arraycopy(data, baseIndex + HEADER_STRIDE, target, targetIndex, QUAD_STRIDE); - - // The color is the fourth integer in each vertex. - // EncodingFormat.VERTEX_COLOR is not used because it also - // contains the header size; vanilla quads do not have a header. - int colorIndex = targetIndex + 3; - - for (int i = 0; i < 4; i++) { - target[colorIndex] = ColorHelper.toVanillaColor(target[colorIndex]); - colorIndex += VANILLA_VERTEX_STRIDE; - } - } - - @Override - public int getFlags() { - return geometryFlags(); - } - - @Override - public float getX(int idx) { - return this.x(idx); - } - - @Override - public float getY(int idx) { - return this.y(idx); - } - - @Override - public float getZ(int idx) { - return this.z(idx); - } - - @Override - public int getColor(int idx) { - return this.color(idx); - } - - @Override - public float getU(int idx) { - return this.u(idx); - } - - @Override - public float getV(int idx) { - return this.v(idx); - } - - @Override - public int getColorIndex() { - return this.colorIndex(); - } - - @Override - public Direction getFacingDirection() { - return this.lightFace(); - } - - @Override - public int getNormal() { - return packedFaceNormal(); - } - - @Override - public QuadFacing getQuadFacing() { - return this.facing; - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java deleted file mode 100644 index 026275612..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractBlockRenderContext.java +++ /dev/null @@ -1,303 +0,0 @@ -package net.vulkanmod.render.chunk.build.frapi.render; - -import it.unimi.dsi.fastutil.objects.Object2ByteLinkedOpenHashMap; -import net.fabricmc.fabric.api.renderer.v1.Renderer; -import net.fabricmc.fabric.api.renderer.v1.RendererAccess; -import net.fabricmc.fabric.api.renderer.v1.model.ModelHelper; -import net.fabricmc.fabric.api.renderer.v1.render.RenderContext; -import net.minecraft.client.Minecraft; -import net.minecraft.client.color.block.BlockColor; -import net.minecraft.client.color.block.BlockColors; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.phys.shapes.BooleanOp; -import net.minecraft.world.phys.shapes.Shapes; -import net.minecraft.world.phys.shapes.VoxelShape; -import net.vulkanmod.interfaces.color.BlockColorsExtended; -import net.vulkanmod.render.chunk.build.color.BlockColorRegistry; -import net.vulkanmod.render.chunk.build.light.LightPipeline; -import net.vulkanmod.render.chunk.build.light.data.QuadLightData; -import org.jetbrains.annotations.Nullable; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; -import net.fabricmc.fabric.api.util.TriState; -import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; -import net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat; -import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; -import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.level.block.state.BlockState; - -import java.util.List; -import java.util.function.Supplier; - -public abstract class AbstractBlockRenderContext extends AbstractRenderContext { - private static final Renderer RENDERER = RendererAccess.INSTANCE.getRenderer(); - protected static final RenderMaterial STANDARD_MATERIAL = RENDERER.materialFinder().shadeMode(ShadeMode.VANILLA).find(); - protected static final RenderMaterial NO_AO_MATERIAL = RENDERER.materialFinder().shadeMode(ShadeMode.VANILLA).ambientOcclusion(TriState.FALSE).find(); - - protected final BlockColorRegistry blockColorRegistry; - - private final MutableQuadViewImpl editorQuad = new MutableQuadViewImpl() { - { - data = new int[EncodingFormat.TOTAL_STRIDE]; - clear(); - } - - @Override - public void emitDirectly() { - renderQuad(this); - } - }; - - protected BlockState blockState; - protected BlockPos blockPos; - protected BlockPos.MutableBlockPos tempPos = new BlockPos.MutableBlockPos(); - - protected BlockAndTintGetter renderRegion; - - protected final Object2ByteLinkedOpenHashMap occlusionCache = new Object2ByteLinkedOpenHashMap<>(2048, 0.25F) { - protected void rehash(int i) { - } - }; - - protected final QuadLightData quadLightData = new QuadLightData(); - protected LightPipeline smoothLightPipeline; - protected LightPipeline flatLightPipeline; - - protected boolean useAO; - protected boolean defaultAO; - - protected long seed; - protected RandomSource random; - public final Supplier randomSupplier = () -> { - long seed = this.seed; - - random.setSeed(seed); - return random; - }; - - protected boolean enableCulling = true; - protected int cullCompletionFlags; - protected int cullResultFlags; - - protected AbstractBlockRenderContext() { - this.occlusionCache.defaultReturnValue((byte) 127); - - BlockColors blockColors = Minecraft.getInstance().getBlockColors(); - this.blockColorRegistry = BlockColorsExtended.from(blockColors).getColorResolverMap(); - } - - protected void setupLightPipelines(LightPipeline flatLightPipeline, LightPipeline smoothLightPipeline) { - this.flatLightPipeline = flatLightPipeline; - this.smoothLightPipeline = smoothLightPipeline; - } - - @Override - public QuadEmitter getEmitter() { - editorQuad.clear(); - return editorQuad; - } - - @Override - public ItemDisplayContext itemTransformationMode() { - throw new IllegalStateException("itemTransformationMode() can only be called on an item render context."); - } - - @SuppressWarnings("removal") - @Override - public BakedModelConsumer bakedModelConsumer() { - return null; - } - - public void prepareForWorld(BlockAndTintGetter blockView, boolean enableCulling) { - this.renderRegion = blockView; - this.enableCulling = enableCulling; - } - - public void prepareForBlock(BlockState blockState, BlockPos blockPos, boolean modelAo) { - this.blockPos = blockPos; - this.blockState = blockState; - - this.useAO = Minecraft.useAmbientOcclusion(); - this.defaultAO = this.useAO && modelAo && blockState.getLightEmission() == 0; - - this.cullCompletionFlags = 0; - this.cullResultFlags = 0; - } - - @Override - public boolean isFaceCulled(@Nullable Direction face) { - return !this.shouldRenderFace(face); - } - - public boolean shouldRenderFace(Direction face) { - if (face == null || !enableCulling) { - return true; - } - - final int mask = 1 << face.get3DDataValue(); - - if ((cullCompletionFlags & mask) == 0) { - cullCompletionFlags |= mask; - - if (this.faceNotOccluded(blockState, face)) { - cullResultFlags |= mask; - return true; - } else { - return false; - } - } else { - return (cullResultFlags & mask) != 0; - } - } - - public boolean faceNotOccluded(BlockState blockState, Direction face) { - BlockGetter blockGetter = this.renderRegion; - - BlockPos adjPos = tempPos.setWithOffset(blockPos, face); - BlockState adjBlockState = blockGetter.getBlockState(adjPos); - - if (blockState.skipRendering(adjBlockState, face)) { - return false; - } - - if (adjBlockState.canOcclude()) { - VoxelShape shape = blockState.getFaceOcclusionShape(blockGetter, blockPos, face); - - if (shape.isEmpty()) - return true; - - VoxelShape adjShape = adjBlockState.getFaceOcclusionShape(blockGetter, adjPos, face.getOpposite()); - - if (adjShape.isEmpty()) - return true; - - if (shape == Shapes.block() && adjShape == Shapes.block()) { - return false; - } - - Block.BlockStatePairKey blockStatePairKey = new Block.BlockStatePairKey(blockState, adjBlockState, face); - - byte b = occlusionCache.getAndMoveToFirst(blockStatePairKey); - if (b != 127) { - return b != 0; - } else { - boolean bl = Shapes.joinIsNotEmpty(shape, adjShape, BooleanOp.ONLY_FIRST); - - if (occlusionCache.size() == 2048) { - occlusionCache.removeLastByte(); - } - - occlusionCache.putAndMoveToFirst(blockStatePairKey, (byte) (bl ? 1 : 0)); - return bl; - } - } - - return true; - } - - private void renderQuad(MutableQuadViewImpl quad) { - if (!transform(quad)) { - return; - } - - if (isFaceCulled(quad.cullFace())) { - return; - } - - endRenderQuad(quad); - } - - protected void endRenderQuad(MutableQuadViewImpl quad) {} - - /** handles block color, common to all renders. */ - protected void colorizeQuad(MutableQuadViewImpl quad, int colorIndex) { - if (colorIndex != -1) { - final int blockColor = getBlockColor(this.renderRegion, colorIndex); - - for (int i = 0; i < 4; i++) { - quad.color(i, ColorHelper.multiplyColor(blockColor, quad.color(i))); - } - } - } - - private int getBlockColor(BlockAndTintGetter region, int colorIndex) { - BlockColor blockColor = this.blockColorRegistry.getBlockColor(this.blockState.getBlock()); - - int color = blockColor != null ? blockColor.getColor(blockState, region, blockPos, colorIndex) : -1; - return 0xFF000000 | color; - } - - protected void shadeQuad(MutableQuadViewImpl quad, LightPipeline lightPipeline, boolean emissive, boolean vanillaShade) { - QuadLightData data = this.quadLightData; - - // TODO: enhanced AO - lightPipeline.calculate(quad, this.blockPos, data, quad.cullFace(), quad.lightFace(), quad.hasShade()); - - if (emissive) { - for (int i = 0; i < 4; i++) { - quad.color(i, ColorHelper.multiplyRGB(quad.color(i), data.br[i])); - data.lm[i] = LightTexture.FULL_BRIGHT; - } - } else { - for (int i = 0; i < 4; i++) { - quad.color(i, ColorHelper.multiplyRGB(quad.color(i), data.br[i])); - data.lm[i] = ColorHelper.maxBrightness(quad.lightmap(i), data.lm[i]); - } - } - } - - public void emitBlockQuads(BakedModel model, @Nullable BlockState state, Supplier randomSupplier, RenderContext context) { - MutableQuadViewImpl quad = this.editorQuad; - final RenderMaterial defaultMaterial = model.useAmbientOcclusion() ? STANDARD_MATERIAL : NO_AO_MATERIAL; - - boolean noTransform = !this.hasTransform(); - - if (noTransform) { - for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { - final Direction cullFace = ModelHelper.faceFromIndex(i); - - if (context.isFaceCulled(cullFace)) { - // Skip entire quad list if possible. - continue; - } - - final List quads = model.getQuads(state, cullFace, randomSupplier.get()); - final int count = quads.size(); - - //noinspection ForLoopReplaceableByForEach - for (int j = 0; j < count; j++) { - final BakedQuad q = quads.get(j); - quad.fromVanilla(q, defaultMaterial, cullFace); - - this.endRenderQuad(quad); - } - } - } else { - for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { - final Direction cullFace = ModelHelper.faceFromIndex(i); - - final List quads = model.getQuads(state, cullFace, randomSupplier.get()); - final int count = quads.size(); - - //noinspection ForLoopReplaceableByForEach - for (int j = 0; j < count; j++) { - final BakedQuad q = quads.get(j); - quad.fromVanilla(q, defaultMaterial, cullFace); - - this.renderQuad(quad); - } - } - } - - } - -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java deleted file mode 100644 index 5048e0874..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/AbstractRenderContext.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.render; - -import java.util.function.Consumer; -import com.mojang.blaze3d.vertex.VertexConsumer; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import org.joml.Matrix3f; -import org.joml.Matrix4f; -import org.joml.Vector3f; -import org.joml.Vector4f; -import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh; -import net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView; -import net.fabricmc.fabric.api.renderer.v1.render.RenderContext; -import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; - -abstract class AbstractRenderContext implements RenderContext { - private static final QuadTransform NO_TRANSFORM = q -> true; - - private QuadTransform activeTransform = NO_TRANSFORM; - private final ObjectArrayList transformStack = new ObjectArrayList<>(); - private final QuadTransform stackTransform = q -> { - int i = transformStack.size() - 1; - - while (i >= 0) { - if (!transformStack.get(i--).transform(q)) { - return false; - } - } - - return true; - }; - - @Deprecated - private final Consumer meshConsumer = mesh -> mesh.outputTo(getEmitter()); - - protected Matrix4f matrix; - protected Matrix3f normalMatrix; - protected int overlay; - private final Vector4f posVec = new Vector4f(); - private final Vector3f normalVec = new Vector3f(); - - protected final boolean transform(MutableQuadView q) { - return activeTransform.transform(q); - } - - @Override - public boolean hasTransform() { - return activeTransform != NO_TRANSFORM; - } - - @Override - public void pushTransform(QuadTransform transform) { - if (transform == null) { - throw new NullPointerException("Renderer received null QuadTransform."); - } - - transformStack.push(transform); - - if (transformStack.size() == 1) { - activeTransform = transform; - } else if (transformStack.size() == 2) { - activeTransform = stackTransform; - } - } - - @Override - public void popTransform() { - transformStack.pop(); - - if (transformStack.size() == 0) { - activeTransform = NO_TRANSFORM; - } else if (transformStack.size() == 1) { - activeTransform = transformStack.get(0); - } - } - - // Overridden to prevent allocating a lambda every time this method is called. - @Deprecated - @Override - public Consumer meshConsumer() { - return meshConsumer; - } - - /** final output step, common to all renders. */ - protected void bufferQuad(MutableQuadViewImpl quad, VertexConsumer vertexConsumer) { - final Vector4f posVec = this.posVec; - final Vector3f normalVec = this.normalVec; - final boolean useNormals = quad.hasVertexNormals(); - - if (useNormals) { - quad.populateMissingNormals(); - } else { - normalVec.set(quad.faceNormal()); - normalVec.mul(normalMatrix); - } - - for (int i = 0; i < 4; i++) { - posVec.set(quad.x(i), quad.y(i), quad.z(i), 1.0f); - posVec.mul(matrix); - vertexConsumer.addVertex(posVec.x(), posVec.y(), posVec.z()); - - final int color = quad.color(i); - vertexConsumer.setColor(color); - vertexConsumer.setUv(quad.u(i), quad.v(i)); - vertexConsumer.setOverlay(overlay); - vertexConsumer.setLight(quad.lightmap(i)); - - if (useNormals) { - quad.copyNormal(i, normalVec); - normalVec.mul(normalMatrix); - } - - vertexConsumer.setNormal(normalVec.x(), normalVec.y(), normalVec.z()); - } - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java deleted file mode 100644 index 4ea9392be..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/BlockRenderContext.java +++ /dev/null @@ -1,90 +0,0 @@ -package net.vulkanmod.render.chunk.build.frapi.render; - -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; -import net.fabricmc.fabric.api.util.TriState; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.Vec3; -import net.vulkanmod.Initializer; -import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; -import net.vulkanmod.render.chunk.build.light.LightMode; -import net.vulkanmod.render.chunk.build.light.LightPipeline; -import net.vulkanmod.render.chunk.build.light.data.ArrayLightDataCache; -import net.vulkanmod.render.chunk.build.light.flat.FlatLightPipeline; -import net.vulkanmod.render.chunk.build.light.smooth.NewSmoothLightPipeline; -import net.vulkanmod.render.chunk.build.light.smooth.SmoothLightPipeline; - -/** - * Context for non-terrain block rendering. - */ -public class BlockRenderContext extends AbstractBlockRenderContext { - private VertexConsumer vertexConsumer; - - private final ArrayLightDataCache lightDataCache = new ArrayLightDataCache(); - - public BlockRenderContext() { - LightPipeline flatLightPipeline = new FlatLightPipeline(this.lightDataCache); - - LightPipeline smoothLightPipeline; - if (Initializer.CONFIG.ambientOcclusion == LightMode.SUB_BLOCK) { - smoothLightPipeline = new NewSmoothLightPipeline(lightDataCache); - } - else { - smoothLightPipeline = new SmoothLightPipeline(lightDataCache); - } - - this.setupLightPipelines(flatLightPipeline, smoothLightPipeline); - } - - public void render(BlockAndTintGetter blockView, BakedModel model, BlockState state, BlockPos pos, PoseStack matrixStack, VertexConsumer buffer, boolean cull, RandomSource random, long seed, int overlay) { - Vec3 offset = state.getOffset(blockView, pos); - matrixStack.translate(offset.x, offset.y, offset.z); - - this.blockPos = pos; - this.vertexConsumer = buffer; - this.matrix = matrixStack.last().pose(); - this.normalMatrix = matrixStack.last().normal(); - this.overlay = overlay; - - this.random = random; - this.seed = seed; - - this.lightDataCache.reset(blockView, pos); - - this.prepareForWorld(blockView, cull); - this.prepareForBlock(state, pos, model.useAmbientOcclusion()); - - model.emitBlockQuads(blockView, state, pos, this.randomSupplier, this); - - this.vertexConsumer = null; - } - - protected void endRenderQuad(MutableQuadViewImpl quad) { - final RenderMaterial mat = quad.material(); - final int colorIndex = mat.disableColorIndex() ? -1 : quad.colorIndex(); - final TriState aoMode = mat.ambientOcclusion(); - final boolean ao = this.useAO && (aoMode == TriState.TRUE || (aoMode == TriState.DEFAULT && this.defaultAO)); - final boolean emissive = mat.emissive(); - final boolean vanillaShade = mat.shadeMode() == ShadeMode.VANILLA; - - LightPipeline lightPipeline = ao ? this.smoothLightPipeline : this.flatLightPipeline; - - colorizeQuad(quad, colorIndex); - shadeQuad(quad, lightPipeline, emissive, vanillaShade); - copyLightData(quad); - bufferQuad(quad, vertexConsumer); - } - - private void copyLightData(MutableQuadViewImpl quad) { - for (int i = 0; i < 4; i++) { - quad.lightmap(i, this.quadLightData.lm[i]); - } - } - -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java b/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java deleted file mode 100644 index 0aef4c9a8..000000000 --- a/src/main/java/net/vulkanmod/render/chunk/build/frapi/render/ItemRenderContext.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright (c) 2016, 2017, 2018, 2019 FabricMC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.vulkanmod.render.chunk.build.frapi.render; - -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import com.mojang.math.MatrixUtil; - -import java.util.List; -import java.util.function.Supplier; - -import net.fabricmc.fabric.api.renderer.v1.model.ModelHelper; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.vulkanmod.mixin.render.frapi.ItemRendererAccessor; -import org.jetbrains.annotations.Nullable; -import net.minecraft.client.Minecraft; -import net.minecraft.client.color.item.ItemColors; -import net.minecraft.client.renderer.ItemBlockRenderTypes; -import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.Sheets; -import net.minecraft.client.renderer.entity.ItemRenderer; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.state.BlockState; -import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; -import net.fabricmc.fabric.api.util.TriState; -import net.vulkanmod.render.chunk.build.frapi.helper.ColorHelper; -import net.vulkanmod.render.chunk.build.frapi.mesh.EncodingFormat; -import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; -import net.fabricmc.fabric.impl.renderer.VanillaModelEncoder; - -import static net.vulkanmod.render.chunk.build.frapi.render.AbstractBlockRenderContext.STANDARD_MATERIAL; - -/** - * The render context used for item rendering. - */ -@SuppressWarnings("removal") -public class ItemRenderContext extends AbstractRenderContext { - /** Value vanilla uses for item rendering. The only sensible choice, of course. */ - private static final long ITEM_RANDOM_SEED = 42L; - - private final ItemColors itemColors; - private final RandomSource random = RandomSource.create(); - private final Supplier randomSupplier = () -> { - random.setSeed(ITEM_RANDOM_SEED); - return random; - }; - - private final MutableQuadViewImpl editorQuad = new MutableQuadViewImpl() { - { - data = new int[EncodingFormat.TOTAL_STRIDE]; - clear(); - } - - @Override - public void emitDirectly() { - renderQuad(this); - } - }; - - private final BakedModelConsumerImpl vanillaModelConsumer = new BakedModelConsumerImpl(); - - private ItemStack itemStack; - private ItemDisplayContext transformMode; - private PoseStack matrixStack; - private MultiBufferSource vertexConsumerProvider; - private int lightmap; - - private boolean isDefaultTranslucent; - private boolean isTranslucentDirect; - private boolean isDefaultGlint; - private boolean isGlintDynamicDisplay; - - private PoseStack.Pose dynamicDisplayGlintEntry; - private VertexConsumer translucentVertexConsumer; - private VertexConsumer cutoutVertexConsumer; - private VertexConsumer translucentGlintVertexConsumer; - private VertexConsumer cutoutGlintVertexConsumer; - - public ItemRenderContext(ItemColors itemColors) { - this.itemColors = itemColors; - } - - @Override - public QuadEmitter getEmitter() { - editorQuad.clear(); - return editorQuad; - } - - @Override - public boolean isFaceCulled(@Nullable Direction face) { - throw new IllegalStateException("isFaceCulled can only be called on a block render context."); - } - - @Override - public ItemDisplayContext itemTransformationMode() { - return transformMode; - } - - @Override - public BakedModelConsumer bakedModelConsumer() { - return vanillaModelConsumer; - } - - public void renderModel(ItemStack itemStack, ItemDisplayContext transformMode, boolean invert, PoseStack matrixStack, MultiBufferSource vertexConsumerProvider, int lightmap, int overlay, BakedModel model) { - this.itemStack = itemStack; - this.transformMode = transformMode; - this.matrixStack = matrixStack; - this.vertexConsumerProvider = vertexConsumerProvider; - this.lightmap = lightmap; - this.overlay = overlay; - computeOutputInfo(); - - matrix = matrixStack.last().pose(); - normalMatrix = matrixStack.last().normal(); - - model.emitItemQuads(itemStack, randomSupplier, this); - - this.itemStack = null; - this.matrixStack = null; - this.vertexConsumerProvider = null; - - dynamicDisplayGlintEntry = null; - translucentVertexConsumer = null; - cutoutVertexConsumer = null; - translucentGlintVertexConsumer = null; - cutoutGlintVertexConsumer = null; - } - - public void emitItemQuads(BakedModel model, @Nullable BlockState state, Supplier randomSupplier) { - if (!this.hasTransform()) { - for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { - final Direction cullFace = ModelHelper.faceFromIndex(i); - final List quads = model.getQuads(state, cullFace, randomSupplier.get()); - final int count = quads.size(); - - //noinspection ForLoopReplaceableByForEach - for (int j = 0; j < count; j++) { - final BakedQuad q = quads.get(j); - editorQuad.fromVanilla(q, STANDARD_MATERIAL, cullFace); - - endRenderQuad(editorQuad); - } - } - } - else { - for (int i = 0; i <= ModelHelper.NULL_FACE_ID; i++) { - final Direction cullFace = ModelHelper.faceFromIndex(i); - final List quads = model.getQuads(state, cullFace, randomSupplier.get()); - final int count = quads.size(); - - //noinspection ForLoopReplaceableByForEach - for (int j = 0; j < count; j++) { - final BakedQuad q = quads.get(j); - editorQuad.fromVanilla(q, STANDARD_MATERIAL, cullFace); - - this.renderQuad(editorQuad); - } - } - } - } - - private void computeOutputInfo() { - isDefaultTranslucent = true; - isTranslucentDirect = true; - - Item item = itemStack.getItem(); - - if (item instanceof BlockItem blockItem) { - BlockState state = blockItem.getBlock().defaultBlockState(); - RenderType renderLayer = ItemBlockRenderTypes.getChunkRenderType(state); - - if (renderLayer != RenderType.translucent()) { - isDefaultTranslucent = false; - } - - if (transformMode != ItemDisplayContext.GUI && !transformMode.firstPerson()) { - isTranslucentDirect = false; - } - } - - isDefaultGlint = itemStack.hasFoil(); - isGlintDynamicDisplay = ItemRendererAccessor.hasAnimatedTexture(itemStack); - } - - private void renderQuad(MutableQuadViewImpl quad) { - if (!transform(quad)) { - return; - } - - endRenderQuad(quad); - } - - private void endRenderQuad(MutableQuadViewImpl quad) { - final RenderMaterial mat = quad.material(); - final int colorIndex = mat.disableColorIndex() ? -1 : quad.colorIndex(); - final boolean emissive = mat.emissive(); - final VertexConsumer vertexConsumer = getVertexConsumer(mat.blendMode(), mat.glint()); - - colorizeQuad(quad, colorIndex); - shadeQuad(quad, emissive); - bufferQuad(quad, vertexConsumer); - } - - private void colorizeQuad(MutableQuadViewImpl quad, int colorIndex) { - if (colorIndex != -1) { - final int itemColor = itemColors.getColor(itemStack, colorIndex); - - for (int i = 0; i < 4; i++) { - quad.color(i, ColorHelper.multiplyColor(itemColor, quad.color(i))); - } - } - } - - private void shadeQuad(MutableQuadViewImpl quad, boolean emissive) { - if (emissive) { - for (int i = 0; i < 4; i++) { - quad.lightmap(i, LightTexture.FULL_BRIGHT); - } - } else { - final int lightmap = this.lightmap; - - for (int i = 0; i < 4; i++) { - quad.lightmap(i, ColorHelper.maxBrightness(quad.lightmap(i), lightmap)); - } - } - } - - /** - * Caches custom blend mode / vertex consumers and mimics the logic - * in {@code RenderLayers.getEntityBlockLayer}. Layers other than - * translucent are mapped to cutout. - */ - private VertexConsumer getVertexConsumer(BlendMode blendMode, TriState glintMode) { - boolean translucent; - boolean glint; - - if (blendMode == BlendMode.DEFAULT) { - translucent = isDefaultTranslucent; - } else { - translucent = blendMode == BlendMode.TRANSLUCENT; - } - - if (glintMode == TriState.DEFAULT) { - glint = isDefaultGlint; - } else { - glint = glintMode == TriState.TRUE; - } - - if (translucent) { - if (glint) { - if (translucentGlintVertexConsumer == null) { - translucentGlintVertexConsumer = createTranslucentVertexConsumer(true); - } - - return translucentGlintVertexConsumer; - } else { - if (translucentVertexConsumer == null) { - translucentVertexConsumer = createTranslucentVertexConsumer(false); - } - - return translucentVertexConsumer; - } - } else { - if (glint) { - if (cutoutGlintVertexConsumer == null) { - cutoutGlintVertexConsumer = createCutoutVertexConsumer(true); - } - - return cutoutGlintVertexConsumer; - } else { - if (cutoutVertexConsumer == null) { - cutoutVertexConsumer = createCutoutVertexConsumer(false); - } - - return cutoutVertexConsumer; - } - } - } - - private VertexConsumer createTranslucentVertexConsumer(boolean glint) { - if (glint && isGlintDynamicDisplay) { - return createDynamicDisplayGlintVertexConsumer(Minecraft.useShaderTransparency() && !isTranslucentDirect ? Sheets.translucentItemSheet() : Sheets.translucentCullBlockSheet()); - } - - if (isTranslucentDirect) { - return ItemRenderer.getFoilBufferDirect(vertexConsumerProvider, Sheets.translucentCullBlockSheet(), true, glint); - } else if (Minecraft.useShaderTransparency()) { - return ItemRenderer.getFoilBuffer(vertexConsumerProvider, Sheets.translucentItemSheet(), true, glint); - } else { - return ItemRenderer.getFoilBuffer(vertexConsumerProvider, Sheets.translucentCullBlockSheet(), true, glint); - } - } - - private VertexConsumer createCutoutVertexConsumer(boolean glint) { - if (glint && isGlintDynamicDisplay) { - return createDynamicDisplayGlintVertexConsumer(Sheets.cutoutBlockSheet()); - } - - return ItemRenderer.getFoilBufferDirect(vertexConsumerProvider, Sheets.cutoutBlockSheet(), true, glint); - } - - private VertexConsumer createDynamicDisplayGlintVertexConsumer(RenderType layer) { - if (dynamicDisplayGlintEntry == null) { - dynamicDisplayGlintEntry = matrixStack.last().copy(); - - if (transformMode == ItemDisplayContext.GUI) { - MatrixUtil.mulComponentWise(dynamicDisplayGlintEntry.pose(), 0.5F); - } else if (transformMode.firstPerson()) { - MatrixUtil.mulComponentWise(dynamicDisplayGlintEntry.pose(), 0.75F); - } - } - - return ItemRenderer.getCompassFoilBuffer(vertexConsumerProvider, layer, dynamicDisplayGlintEntry); - } - - private class BakedModelConsumerImpl implements BakedModelConsumer { - @Override - public void accept(BakedModel model) { - accept(model, null); - } - - @Override - public void accept(BakedModel model, @Nullable BlockState state) { - VanillaModelEncoder.emitItemQuads(model, state, randomSupplier, ItemRenderContext.this); - } - } -} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/LightMode.java b/src/main/java/net/vulkanmod/render/chunk/build/light/LightMode.java index cc82f119a..339138466 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/LightMode.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/LightMode.java @@ -4,4 +4,4 @@ public abstract class LightMode { public static final int FLAT = 0; public static final int SMOOTH = 1; public static final int SUB_BLOCK = 2; -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/LightPipeline.java b/src/main/java/net/vulkanmod/render/chunk/build/light/LightPipeline.java index 69d3c184e..fc4ec50a3 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/LightPipeline.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/LightPipeline.java @@ -2,22 +2,23 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.vulkanmod.render.model.quad.ModelQuadView; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; +import net.vulkanmod.render.model.quad.ModelQuadView; /** * Light pipelines allow model quads for any location in the world to be lit using various backends, including fluids - * and block entities. + * and block entities. */ public interface LightPipeline { /** * Calculates the light data for a given block model quad, storing the result in {@param out}. - * @param quad The block model quad - * @param pos The block position of the model this quad belongs to - * @param out The data arrays which will store the calculated light data results - * @param cullFace The cull face of the quad + * + * @param quad The block model quad + * @param pos The block position of the model this quad belongs to + * @param out The data arrays which will store the calculated light data results + * @param cullFace The cull face of the quad * @param lightFace The light face of the quad - * @param shade True if the block is shaded by ambient occlusion + * @param shade True if the block is shaded by ambient occlusion */ void calculate(ModelQuadView quad, BlockPos pos, QuadLightData out, Direction cullFace, Direction lightFace, boolean shade); -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java b/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java index 1312b4671..c04ddc9ef 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/data/LightDataAccess.java @@ -42,100 +42,14 @@ public abstract class LightDataAccess { private static final int FC_OFFSET = 31; private static final float AO_INV = 1.0f / 2048.0f; - + final boolean subBlockLighting; private final BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(); protected BlockAndTintGetter region; - final boolean subBlockLighting; - protected LightDataAccess() { this.subBlockLighting = Initializer.CONFIG.ambientOcclusion == LightMode.SUB_BLOCK; } - public int get(int x, int y, int z, SimpleDirection d1, SimpleDirection d2) { - return this.get(x + d1.getStepX() + d2.getStepX(), - y + d1.getStepY() + d2.getStepY(), - z + d1.getStepZ() + d2.getStepZ()); - } - - public int get(int x, int y, int z, SimpleDirection dir) { - return this.get(x + dir.getStepX(), - y + dir.getStepY(), - z + dir.getStepZ()); - } - - public int get(BlockPos pos, SimpleDirection dir) { - return this.get(pos.getX(), pos.getY(), pos.getZ(), dir); - } - - public int get(BlockPos pos) { - return this.get(pos.getX(), pos.getY(), pos.getZ()); - } - - /** - * Returns the light data for the block at the given position. The property fields can then be accessed using - * the various unpack methods below. - */ - public abstract int get(int x, int y, int z); - - protected int compute(int x, int y, int z) { - BlockPos pos = this.pos.set(x, y, z); - BlockState state = region.getBlockState(pos); - - boolean em = state.emissiveRendering(region, pos); - - boolean op; - if (this.subBlockLighting) - op = state.canOcclude(); - else - op = state.isViewBlocking(region, pos) && state.getLightBlock(region, pos) != 0; - - boolean fo = state.isSolidRender(region, pos); - boolean fc = state.isCollisionShapeFullBlock(region, pos); - - int lu = state.getLightEmission(); - - // OPTIMIZE: Do not calculate light data if the block is full and opaque and does not emit light. - int bl; - int sl; - if (fo && lu == 0) { - bl = 0; - sl = 0; - } - else { - if (em) { - bl = region.getBrightness(LightLayer.BLOCK, pos); - sl = region.getBrightness(LightLayer.SKY, pos); - } - else { - int light = LevelRenderer.getLightColor(region, state, pos); - bl = LightTexture.block(light); - sl = LightTexture.sky(light); - } - } - - // FIX: Do not apply AO from blocks that emit light - float ao; - if (lu == 0) { - ao = state.getShadeBrightness(region, pos); - } - else { - ao = 1.0f; - } - - boolean useAo = ao < 1.0f; - - bl = Math.max(bl, lu); - - int crs = (fo || fc) && lu == 0 && useAo ? 0xFF : 0; - if (!fo && op) { - VoxelShape shape = state.getShape(region, pos); - crs = ((VoxelShapeExtended) (shape)).getCornerOcclusion(); - } - - return packFC(fc) | packFO(fo) | packOP(op) | packEM(em) | packCO(crs) | packAO(ao) | packSL(sl) | packBL(bl); - } - public static int packBL(int blockLight) { return (blockLight & 0xF) << BL_OFFSET; } @@ -217,13 +131,89 @@ public static int getLightmap(int word) { public static int getEmissiveLightmap(int word) { if (unpackEM(word)) { return LightTexture.FULL_BRIGHT; - } - else { + } else { return getLightmap(word); } } + public int get(int x, int y, int z, SimpleDirection d1, SimpleDirection d2) { + return this.get(x + d1.getStepX() + d2.getStepX(), + y + d1.getStepY() + d2.getStepY(), + z + d1.getStepZ() + d2.getStepZ()); + } + + public int get(int x, int y, int z, SimpleDirection dir) { + return this.get(x + dir.getStepX(), + y + dir.getStepY(), + z + dir.getStepZ()); + } + + public int get(BlockPos pos, SimpleDirection dir) { + return this.get(pos.getX(), pos.getY(), pos.getZ(), dir); + } + + public int get(BlockPos pos) { + return this.get(pos.getX(), pos.getY(), pos.getZ()); + } + + /** + * Returns the light data for the block at the given position. The property fields can then be accessed using + * the various unpack methods below. + */ + public abstract int get(int x, int y, int z); + + protected int compute(int x, int y, int z) { + BlockPos pos = this.pos.set(x, y, z); + BlockState state = region.getBlockState(pos); + + boolean em = state.emissiveRendering(region, pos); + + boolean op = this.subBlockLighting ? state.canOcclude() : (state.isSolidRender() && state.getLightBlock() != 0); + + boolean fo = state.isSolidRender(); + boolean fc = state.isCollisionShapeFullBlock(region, pos); + + int lu = state.getLightEmission(); + + // OPTIMIZE: Do not calculate light data if the block is full and opaque and does not emit light. + int bl; + int sl; + if (fo && lu == 0) { + bl = 0; + sl = 0; + } else { + if (em) { + bl = region.getBrightness(LightLayer.BLOCK, pos); + sl = region.getBrightness(LightLayer.SKY, pos); + } else { + int light = LevelRenderer.getLightColor(region, pos); + bl = LightTexture.block(light); + sl = LightTexture.sky(light); + } + } + + // FIX: Do not apply AO from blocks that emit light + float ao; + if (lu == 0) { + ao = state.getShadeBrightness(region, pos); + } else { + ao = 1.0f; + } + + boolean useAo = ao < 1.0f; + + bl = Math.max(bl, lu); + + int crs = (fo || fc) && lu == 0 && useAo ? 0xFF : 0; + if (!fo && op) { + VoxelShape shape = state.getShape(region, pos); + crs = ((VoxelShapeExtended) (shape)).getCornerOcclusion(); + } + + return packFC(fc) | packFO(fo) | packOP(op) | packEM(em) | packCO(crs) | packAO(ao) | packSL(sl) | packBL(bl); + } + public BlockAndTintGetter getRegion() { return this.region; } -} \ No newline at end of file +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/data/QuadLightData.java b/src/main/java/net/vulkanmod/render/chunk/build/light/data/QuadLightData.java index 6014eaf6a..6d1ab0029 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/data/QuadLightData.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/data/QuadLightData.java @@ -14,4 +14,4 @@ public class QuadLightData { * The lightmap texture coordinates for each vertex in the quad. */ public final int[] lm = new int[4]; -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/flat/FlatLightPipeline.java b/src/main/java/net/vulkanmod/render/chunk/build/light/flat/FlatLightPipeline.java index b11f4e352..333c09f0f 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/flat/FlatLightPipeline.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/flat/FlatLightPipeline.java @@ -3,12 +3,12 @@ import net.minecraft.client.renderer.LightTexture; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.vulkanmod.render.chunk.util.SimpleDirection; -import net.vulkanmod.render.model.quad.ModelQuadView; -import net.vulkanmod.render.chunk.build.light.data.LightDataAccess; import net.vulkanmod.render.chunk.build.light.LightPipeline; +import net.vulkanmod.render.chunk.build.light.data.LightDataAccess; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; +import net.vulkanmod.render.chunk.util.SimpleDirection; import net.vulkanmod.render.model.quad.ModelQuadFlags; +import net.vulkanmod.render.model.quad.ModelQuadView; import java.util.Arrays; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/AoFaceData.java b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/AoFaceData.java index d4be249f3..9d51ea902 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/AoFaceData.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/AoFaceData.java @@ -2,8 +2,8 @@ import net.minecraft.client.renderer.LightTexture; import net.minecraft.core.BlockPos; -import net.vulkanmod.render.chunk.util.SimpleDirection; import net.vulkanmod.render.chunk.build.light.data.LightDataAccess; +import net.vulkanmod.render.chunk.util.SimpleDirection; import static net.vulkanmod.render.chunk.build.light.data.LightDataAccess.*; @@ -16,6 +16,65 @@ class AoFaceData { protected int flags; + static float weightedSum(float[] v, float[] w) { + float t0 = v[0] * w[0]; + float t1 = v[1] * w[1]; + float t2 = v[2] * w[2]; + float t3 = v[3] * w[3]; + + return t0 + t1 + t2 + t3; + } + + static float unpackSkyLight(int i) { + return (i >> 16) & 0xFF; + } + + static float unpackBlockLight(int i) { + return i & 0xFF; + } + + static int calculateCornerBrightness(int a, int b, int c, int d, boolean aem, boolean bem, boolean cem, boolean dem) { + // FIX: Normalize corner vectors correctly to the minimum non-zero value between each one to prevent + // strange issues + if ((a == 0) || (b == 0) || (c == 0) || (d == 0)) { + // Find the minimum value between all corners + final int min = minNonZero(minNonZero(a, b), minNonZero(c, d)); + + // Normalize the corner values + a = Math.max(a, min); + b = Math.max(b, min); + c = Math.max(c, min); + d = Math.max(d, min); + } + + // FIX: Apply the fullbright lightmap from emissive blocks at the very end so it cannot influence + // the minimum lightmap and produce incorrect results (for example, sculk sensors in a dark room) + if (aem) { + a = LightTexture.FULL_BRIGHT; + } + if (bem) { + b = LightTexture.FULL_BRIGHT; + } + if (cem) { + c = LightTexture.FULL_BRIGHT; + } + if (dem) { + d = LightTexture.FULL_BRIGHT; + } + + return ((a + b + c + d) >> 2) & 0xFF00FF; + } + + static int minNonZero(int a, int b) { + if (a == 0) { + return b; + } else if (b == 0) { + return a; + } + + return Math.min(a, b); + } + public void initLightData(LightDataAccess cache, BlockPos pos, SimpleDirection direction, boolean offset) { final int oX = pos.getX(); final int oY = pos.getY(); @@ -191,65 +250,6 @@ public float getBlendedShade(float[] w) { return weightedSum(this.ao, w); } - static float weightedSum(float[] v, float[] w) { - float t0 = v[0] * w[0]; - float t1 = v[1] * w[1]; - float t2 = v[2] * w[2]; - float t3 = v[3] * w[3]; - - return t0 + t1 + t2 + t3; - } - - static float unpackSkyLight(int i) { - return (i >> 16) & 0xFF; - } - - static float unpackBlockLight(int i) { - return i & 0xFF; - } - - static int calculateCornerBrightness(int a, int b, int c, int d, boolean aem, boolean bem, boolean cem, boolean dem) { - // FIX: Normalize corner vectors correctly to the minimum non-zero value between each one to prevent - // strange issues - if ((a == 0) || (b == 0) || (c == 0) || (d == 0)) { - // Find the minimum value between all corners - final int min = minNonZero(minNonZero(a, b), minNonZero(c, d)); - - // Normalize the corner values - a = Math.max(a, min); - b = Math.max(b, min); - c = Math.max(c, min); - d = Math.max(d, min); - } - - // FIX: Apply the fullbright lightmap from emissive blocks at the very end so it cannot influence - // the minimum lightmap and produce incorrect results (for example, sculk sensors in a dark room) - if (aem) { - a = LightTexture.FULL_BRIGHT; - } - if (bem) { - b = LightTexture.FULL_BRIGHT; - } - if (cem) { - c = LightTexture.FULL_BRIGHT; - } - if (dem) { - d = LightTexture.FULL_BRIGHT; - } - - return ((a + b + c + d) >> 2) & 0xFF00FF; - } - - static int minNonZero(int a, int b) { - if (a == 0) { - return b; - } else if (b == 0) { - return a; - } - - return Math.min(a, b); - } - public boolean hasLightData() { return (this.flags & FaceDataFlags.HAS_LIGHT_DATA) != 0; } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/AoNeighborInfo.java b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/AoNeighborInfo.java index c3ccad908..bd68fdc4c 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/AoNeighborInfo.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/AoNeighborInfo.java @@ -8,10 +8,10 @@ */ @SuppressWarnings("UnnecessaryLocalVariable") enum AoNeighborInfo { - DOWN(new SimpleDirection[] { SimpleDirection.SOUTH, SimpleDirection.WEST, SimpleDirection.NORTH, SimpleDirection.EAST }, - new int[] {4, 5, 6, 7, - 0, 1, 2, 3}, - 0.5F) { + DOWN(new SimpleDirection[]{SimpleDirection.SOUTH, SimpleDirection.WEST, SimpleDirection.NORTH, SimpleDirection.EAST}, + new int[]{4, 5, 6, 7, + 0, 1, 2, 3}, + 0.5F) { @Override public void calculateCornerWeights(float x, float y, float z, float[] out) { final float u = 1.0f - x; @@ -35,10 +35,10 @@ public float getDepth(float x, float y, float z) { return y; } }, - UP(new SimpleDirection[] { SimpleDirection.NORTH, SimpleDirection.WEST, SimpleDirection.SOUTH, SimpleDirection.EAST }, - new int[] {2, 3, 0, 1, + UP(new SimpleDirection[]{SimpleDirection.NORTH, SimpleDirection.WEST, SimpleDirection.SOUTH, SimpleDirection.EAST}, + new int[]{2, 3, 0, 1, 6, 7, 4, 5}, - 1.0F) { + 1.0F) { @Override public void calculateCornerWeights(float x, float y, float z, float[] out) { final float u = 1.0f - x; @@ -62,8 +62,8 @@ public float getDepth(float x, float y, float z) { return 1.0f - y; } }, - NORTH(new SimpleDirection[] { SimpleDirection.UP, SimpleDirection.EAST, SimpleDirection.DOWN, SimpleDirection.WEST }, - new int[] {3, 2, 7, 6, + NORTH(new SimpleDirection[]{SimpleDirection.UP, SimpleDirection.EAST, SimpleDirection.DOWN, SimpleDirection.WEST}, + new int[]{3, 2, 7, 6, 1, 0, 5, 4}, 0.8F) { @Override @@ -89,8 +89,8 @@ public float getDepth(float x, float y, float z) { return z; } }, - SOUTH(new SimpleDirection[] { SimpleDirection.UP, SimpleDirection.WEST, SimpleDirection.DOWN, SimpleDirection.EAST }, - new int[] {0, 1, 4, 5, + SOUTH(new SimpleDirection[]{SimpleDirection.UP, SimpleDirection.WEST, SimpleDirection.DOWN, SimpleDirection.EAST}, + new int[]{0, 1, 4, 5, 2, 3, 6, 7}, 0.8F) { @Override @@ -116,8 +116,8 @@ public float getDepth(float x, float y, float z) { return 1.0f - z; } }, - WEST(new SimpleDirection[] { SimpleDirection.UP, SimpleDirection.NORTH, SimpleDirection.DOWN, SimpleDirection.SOUTH }, - new int[] {1, 3, 5, 7, + WEST(new SimpleDirection[]{SimpleDirection.UP, SimpleDirection.NORTH, SimpleDirection.DOWN, SimpleDirection.SOUTH}, + new int[]{1, 3, 5, 7, 0, 2, 4, 6}, 0.6F) { @Override @@ -143,8 +143,8 @@ public float getDepth(float x, float y, float z) { return x; } }, - EAST(new SimpleDirection[] { SimpleDirection.UP, SimpleDirection.SOUTH, SimpleDirection.DOWN, SimpleDirection.NORTH }, - new int[] {2, 0, 6, 4, + EAST(new SimpleDirection[]{SimpleDirection.UP, SimpleDirection.SOUTH, SimpleDirection.DOWN, SimpleDirection.NORTH}, + new int[]{2, 0, 6, 4, 3, 1, 7, 5}, 0.6F) { @Override @@ -171,23 +171,21 @@ public float getDepth(float x, float y, float z) { } }; + private static final AoNeighborInfo[] VALUES = AoNeighborInfo.values(); /** * The direction of each corner block from this face, which can be retrieved by offsetting the position of the origin * block by the direction vector. */ public final SimpleDirection[] faces; - /** * The constant brightness modifier for this face. This data exists to emulate the results of the OpenGL lighting * model which gives a faux directional light appearance to blocks in the game. Not currently used. */ public final float strength; - /** * The indexes of each inner corner occlusion bit for every model vertex. */ public final int[] inCornerBits = new int[4 * 2]; - /** * The indexes of each outer corner occlusion bit for every model vertex. */ @@ -201,55 +199,6 @@ public float getDepth(float x, float y, float z) { getOutCornerBits(this.outCornerBits, indices); } - /** - * Calculates how much each corner contributes to the final "darkening" of the vertex at the specified position. The - * weight is a function of the distance from the vertex's position to the corner block's position. - * - * @param x The x-position of the vertex - * @param y The y-position of the vertex - * @param z The z-position of the vertex - * @param out The weight values for each corner - */ - public abstract void calculateCornerWeights(float x, float y, float z, float[] out); - - public abstract float getU(float x, float y, float z); - - public abstract float getV(float x, float y, float z); - - /** - * Maps the light map and occlusion value arrays {@param lm0} and {@param ao0} from {@link AoFaceData} to the - * correct corners for this facing. - * - * @param lm0 The input light map texture coordinates array - * @param ao0 The input ambient occlusion color array - * @param lm1 The re-orientated output light map texture coordinates array - * @param ao1 The re-orientated output ambient occlusion color array - */ - public void copyLightValues(int[] lm0, float[] ao0, int[] lm1, float[] ao1) { - lm1[0] = lm0[0]; - lm1[1] = lm0[1]; - lm1[2] = lm0[2]; - lm1[3] = lm0[3]; - - ao1[0] = ao0[0]; - ao1[1] = ao0[1]; - ao1[2] = ao0[2]; - ao1[3] = ao0[3]; - } - - /** - * Calculates the depth (or inset) of the vertex into this facing of the block. Used to determine - * how much shadow is contributed by the direct neighbors of a block. - * - * @param x The x-position of the vertex - * @param y The y-position of the vertex - * @param z The z-position of the vertex - * @return The depth of the vertex into this face - */ - public abstract float getDepth(float x, float y, float z); - - private static final AoNeighborInfo[] VALUES = AoNeighborInfo.values(); - /** * @return Returns the {@link AoNeighborInfo} which corresponds with the specified direction */ @@ -319,4 +268,51 @@ private static void getOutCornerBits(int[] cornersBits, int[] idxs) { cornersBits[12 + 10] = idxs[4 + 1]; cornersBits[12 + 11] = idxs[4 + 0]; } + + /** + * Calculates how much each corner contributes to the final "darkening" of the vertex at the specified position. The + * weight is a function of the distance from the vertex's position to the corner block's position. + * + * @param x The x-position of the vertex + * @param y The y-position of the vertex + * @param z The z-position of the vertex + * @param out The weight values for each corner + */ + public abstract void calculateCornerWeights(float x, float y, float z, float[] out); + + public abstract float getU(float x, float y, float z); + + public abstract float getV(float x, float y, float z); + + /** + * Maps the light map and occlusion value arrays {@param lm0} and {@param ao0} from {@link AoFaceData} to the + * correct corners for this facing. + * + * @param lm0 The input light map texture coordinates array + * @param ao0 The input ambient occlusion color array + * @param lm1 The re-orientated output light map texture coordinates array + * @param ao1 The re-orientated output ambient occlusion color array + */ + public void copyLightValues(int[] lm0, float[] ao0, int[] lm1, float[] ao1) { + lm1[0] = lm0[0]; + lm1[1] = lm0[1]; + lm1[2] = lm0[2]; + lm1[3] = lm0[3]; + + ao1[0] = ao0[0]; + ao1[1] = ao0[1]; + ao1[2] = ao0[2]; + ao1[3] = ao0[3]; + } + + /** + * Calculates the depth (or inset) of the vertex into this facing of the block. Used to determine + * how much shadow is contributed by the direct neighbors of a block. + * + * @param x The x-position of the vertex + * @param y The y-position of the vertex + * @param z The z-position of the vertex + * @return The depth of the vertex into this face + */ + public abstract float getDepth(float x, float y, float z); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/FaceDataFlags.java b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/FaceDataFlags.java index 0e2f6a27b..afa7bf3a9 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/FaceDataFlags.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/FaceDataFlags.java @@ -13,4 +13,4 @@ abstract class FaceDataFlags { * The light data has been unpacked into normalized floating point values. */ public static final int HAS_UNPACKED_LIGHT_DATA = 0b10; -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/NewSmoothLightPipeline.java b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/NewSmoothLightPipeline.java index 503d27ff9..81a876727 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/NewSmoothLightPipeline.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/NewSmoothLightPipeline.java @@ -3,12 +3,12 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.util.Mth; -import net.vulkanmod.render.chunk.util.SimpleDirection; -import net.vulkanmod.render.model.quad.ModelQuadView; -import net.vulkanmod.render.chunk.build.light.data.LightDataAccess; import net.vulkanmod.render.chunk.build.light.LightPipeline; +import net.vulkanmod.render.chunk.build.light.data.LightDataAccess; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; +import net.vulkanmod.render.chunk.util.SimpleDirection; import net.vulkanmod.render.model.quad.ModelQuadFlags; +import net.vulkanmod.render.model.quad.ModelQuadView; /** * A smooth light pipeline which introduces sub-block AO computations @@ -25,13 +25,11 @@ public class NewSmoothLightPipeline implements LightPipeline { * Face data to allow face self-occlusion computation. */ private final SubBlockAoFace self = new SubBlockAoFace(); - - private long cachedPos = Long.MIN_VALUE; - /** * A temporary array for storing the intermediary results of weight data for non-aligned face blending. */ private final float[] weights = new float[4]; + private long cachedPos = Long.MIN_VALUE; public NewSmoothLightPipeline(LightDataAccess cache) { this.lightCache = cache; @@ -41,6 +39,26 @@ public NewSmoothLightPipeline(LightDataAccess cache) { } } + /** + * Clamps the given float to the range [0.0, 1.0]. + */ + private static float clamp(float v) { + if (v < 0.0f) { + return 0.0f; + } else if (v > 1.0f) { + return 1.0f; + } + + return v; + } + + /** + * Returns texture coordinates for the light map texture using the given block and sky light values. + */ + private static int packLightMap(float sl, float bl) { + return (((int) sl & 0xFF) << 16) | ((int) bl & 0xFF); + } + @Override public void calculate(ModelQuadView quad, BlockPos pos, QuadLightData out, Direction cullFace, Direction lightFaceO, boolean shade) { this.updateCachedData(pos.asLong()); @@ -260,24 +278,4 @@ private void updateCachedData(long key) { } } - /** - * Clamps the given float to the range [0.0, 1.0]. - */ - private static float clamp(float v) { - if (v < 0.0f) { - return 0.0f; - } else if (v > 1.0f) { - return 1.0f; - } - - return v; - } - - /** - * Returns texture coordinates for the light map texture using the given block and sky light values. - */ - private static int packLightMap(float sl, float bl) { - return (((int) sl & 0xFF) << 16) | ((int) bl & 0xFF); - } - } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SmoothLightPipeline.java b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SmoothLightPipeline.java index 154eb0518..d023fffce 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SmoothLightPipeline.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SmoothLightPipeline.java @@ -3,39 +3,39 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.util.Mth; -import net.vulkanmod.render.chunk.util.SimpleDirection; -import net.vulkanmod.render.model.quad.ModelQuadView; -import net.vulkanmod.render.chunk.build.light.data.LightDataAccess; import net.vulkanmod.render.chunk.build.light.LightPipeline; +import net.vulkanmod.render.chunk.build.light.data.LightDataAccess; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; +import net.vulkanmod.render.chunk.util.SimpleDirection; import net.vulkanmod.render.model.quad.ModelQuadFlags; +import net.vulkanmod.render.model.quad.ModelQuadView; /** * Re-adapted Sodium's smooth light pipeline - * + *

* A light pipeline which produces smooth interpolated lighting and ambient occlusion for model quads. This * implementation makes a number of improvements over vanilla's own "smooth lighting" option. In no particular order: - * + *

* - Corner blocks are now selected from the correct set of neighbors above block faces (fixes MC-148689 and MC-12558) * - Shading issues caused by anisotropy are fixed by re-orientating quads to a consistent ordering (fixes MC-138211) * - Inset block faces are correctly shaded by their neighbors, fixing a number of problems with non-full blocks such as - * grass paths (fixes MC-11783 and MC-108621) + * grass paths (fixes MC-11783 and MC-108621) * - Blocks next to emissive blocks are too bright (MC-260989) * - Synchronization issues between the main render thread's light engine and chunk build worker threads are corrected - * by copying light data alongside block states, fixing a number of inconsistencies in baked chunks (no open issue) - * + * by copying light data alongside block states, fixing a number of inconsistencies in baked chunks (no open issue) + *

* This implementation also includes a significant number of optimizations: - * + *

* - Computed light data for a given block face is cached and re-used again when multiple quads exist for a given - * facing, making complex block models less expensive to render + * facing, making complex block models less expensive to render * - The light data cache encodes as much information as possible into integer words to improve cache locality and - * to eliminate the multiple array lookups that would otherwise be needed, significantly speeding up this section + * to eliminate the multiple array lookups that would otherwise be needed, significantly speeding up this section * - Block faces aligned to the block grid use a fast-path for mapping corner light values to vertices without expensive - * interpolation or blending, speeding up most block renders + * interpolation or blending, speeding up most block renders * - Some critical code paths have been re-written to hit the JVM's happy path, allowing it to perform auto-vectorization - * of the blend functions + * of the blend functions * - Information about a given model quad is cached to enable the light pipeline to make certain assumptions and skip - * unnecessary computation + * unnecessary computation */ public class SmoothLightPipeline implements LightPipeline { /** @@ -47,16 +47,14 @@ public class SmoothLightPipeline implements LightPipeline { * The cached face data for each side of a block, both inner and outer. */ private final AoFaceData[] cachedFaceData = new AoFaceData[6 * 2]; - - /** - * The position at which the cached face data was taken at. - */ - private long cachedPos = Long.MIN_VALUE; - /** * A temporary array for storing the intermediary results of weight data for non-aligned face blending. */ private final float[] weights = new float[4]; + /** + * The position at which the cached face data was taken at. + */ + private long cachedPos = Long.MIN_VALUE; public SmoothLightPipeline(LightDataAccess cache) { this.lightCache = cache; @@ -66,6 +64,20 @@ public SmoothLightPipeline(LightDataAccess cache) { } } + private static float clamp(float v) { + if (v < 0.0f) { + return 0.0f; + } else if (v > 1.0f) { + return 1.0f; + } + + return v; + } + + private static int packLightMap(float sl, float bl) { + return (((int) sl & 0xFF) << 16) | ((int) bl & 0xFF); + } + @Override public void calculate(ModelQuadView quad, BlockPos pos, QuadLightData out, Direction cullFace, Direction lightFaceO, boolean shade) { this.updateCachedData(pos.asLong()); @@ -248,18 +260,4 @@ private void updateCachedData(long key) { } } - private static float clamp(float v) { - if (v < 0.0f) { - return 0.0f; - } else if (v > 1.0f) { - return 1.0f; - } - - return v; - } - - private static int packLightMap(float sl, float bl) { - return (((int) sl & 0xFF) << 16) | ((int) bl & 0xFF); - } - } \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SubBlockAoFace.java b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SubBlockAoFace.java index 765039c17..dee91e210 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SubBlockAoFace.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/light/smooth/SubBlockAoFace.java @@ -1,8 +1,8 @@ package net.vulkanmod.render.chunk.build.light.smooth; import net.minecraft.core.BlockPos; -import net.vulkanmod.render.chunk.util.SimpleDirection; import net.vulkanmod.render.chunk.build.light.data.LightDataAccess; +import net.vulkanmod.render.chunk.util.SimpleDirection; import static net.vulkanmod.render.chunk.build.light.data.LightDataAccess.*; @@ -83,14 +83,13 @@ public void initLightData(LightDataAccess cache, BlockPos pos, SimpleDirection d float c0ao = c0oc ? 0.2f : 1.0f; final boolean c0em; - if((f0c0 && f1c0) || (c0oc && d0co)) { + if ((f0c0 && f1c0) || (c0oc && d0co)) { c0ao = 1.6f; - } - else { + } else { c0ao += f0c0 ? 0.2f : 1.0f; c0ao += f1c0 ? 0.2f : 1.0f; - if(offset) + if (offset) c0ao += d0co ? 0.2f : 1.0f; else c0ao += unpackFO(d0) ? 0.2f : 1.0f; @@ -115,14 +114,13 @@ public void initLightData(LightDataAccess cache, BlockPos pos, SimpleDirection d float c1ao = c1oc ? 0.2f : 1.0f; final boolean c1em; - if((f1c1 && f2c1) || (c1oc && d1co)) { + if ((f1c1 && f2c1) || (c1oc && d1co)) { c1ao = 1.6f; - } - else { + } else { c1ao += f1c1 ? 0.2f : 1.0f; c1ao += f2c1 ? 0.2f : 1.0f; - if(offset) + if (offset) c1ao += d1co ? 0.2f : 1.0f; else c1ao += unpackFO(d1) ? 0.2f : 1.0f; @@ -147,14 +145,13 @@ public void initLightData(LightDataAccess cache, BlockPos pos, SimpleDirection d float c2ao = c2oc ? 0.2f : 1.0f; final boolean c2em; - if((f2c2 && f3c2) || (c2oc && d2co)) { + if ((f2c2 && f3c2) || (c2oc && d2co)) { c2ao = 1.6f; - } - else { + } else { c2ao += f2c2 ? 0.2f : 1.0f; c2ao += f3c2 ? 0.2f : 1.0f; - if(offset) + if (offset) c2ao += d2co ? 0.2f : 1.0f; else c2ao += unpackFO(d2) ? 0.2f : 1.0f; @@ -179,14 +176,13 @@ public void initLightData(LightDataAccess cache, BlockPos pos, SimpleDirection d float c3ao = c3oc ? 0.2f : 1.0f; final boolean c3em; - if((f3c3 && f0c3) || (c3oc && d3co)) { + if ((f3c3 && f0c3) || (c3oc && d3co)) { c3ao = 1.6f; - } - else { + } else { c3ao += f3c3 ? 0.2f : 1.0f; c3ao += f0c3 ? 0.2f : 1.0f; - if(offset) + if (offset) c3ao += d3co ? 0.2f : 1.0f; else c3ao += unpackFO(d3) ? 0.2f : 1.0f; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/pipeline/helper/ColorHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/helper/ColorHelper.java new file mode 100644 index 000000000..fc3408f75 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/helper/ColorHelper.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.pipeline.helper; + +import java.nio.ByteOrder; + +/** + * Static routines of general utility for renderer implementations. + * Renderers are not required to use these helpers, but they were + * designed to be usable without the default renderer. + */ +public abstract class ColorHelper { + private static final boolean BIG_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN; + + private ColorHelper() { + } + + /** + * Component-wise multiply. Components need to be in same order in both inputs! + */ + public static int multiplyColor(int color1, int color2) { + if (color1 == -1) { + return color2; + } else if (color2 == -1) { + return color1; + } + + final int alpha = ((color1 >>> 24) & 0xFF) * ((color2 >>> 24) & 0xFF) / 0xFF; + final int red = ((color1 >>> 16) & 0xFF) * ((color2 >>> 16) & 0xFF) / 0xFF; + final int green = ((color1 >>> 8) & 0xFF) * ((color2 >>> 8) & 0xFF) / 0xFF; + final int blue = (color1 & 0xFF) * (color2 & 0xFF) / 0xFF; + + return (alpha << 24) | (red << 16) | (green << 8) | blue; + } + + /** + * Multiplies three lowest components by shade. High byte (usually alpha) unchanged. + */ + public static int multiplyRGB(int color, float shade) { + final int alpha = ((color >>> 24) & 0xFF); + final int red = (int) (((color >>> 16) & 0xFF) * shade); + final int green = (int) (((color >>> 8) & 0xFF) * shade); + final int blue = (int) ((color & 0xFF) * shade); + + return (alpha << 24) | (red << 16) | (green << 8) | blue; + } + + /** + * Component-wise max. + */ + public static int maxBrightness(int b0, int b1) { + if (b0 == 0) return b1; + if (b1 == 0) return b0; + + return Math.max(b0 & 0xFFFF, b1 & 0xFFFF) | Math.max(b0 & 0xFFFF0000, b1 & 0xFFFF0000); + } + + /* + Renderer color format: ARGB (0xAARRGGBB) + Vanilla color format (little endian): ABGR (0xAABBGGRR) + Vanilla color format (big endian): RGBA (0xRRGGBBAA) + + Why does the vanilla color format change based on endianness? + See VertexConsumer#quad. Quad data is loaded as integers into + a native byte order buffer. Color is read directly from bytes + 12, 13, 14 of each vertex. A different byte order will yield + different results. + + The renderer always uses ARGB because the API color methods + always consume and return ARGB. Vanilla block and item colors + also use ARGB. + */ + + /** + * Converts from ARGB color to ABGR color if little endian or RGBA color if big endian. + */ + public static int toVanillaColor(int color) { + if (color == -1) { + return -1; + } + + if (BIG_ENDIAN) { + // ARGB to RGBA + return ((color & 0x00FFFFFF) << 8) | ((color & 0xFF000000) >>> 24); + } else { + // ARGB to ABGR + return (color & 0xFF00FF00) | ((color & 0x00FF0000) >>> 16) | ((color & 0x000000FF) << 16); + } + } + + /** + * Converts to ARGB color from ABGR color if little endian or RGBA color if big endian. + */ + public static int fromVanillaColor(int color) { + if (color == -1) { + return -1; + } + + if (BIG_ENDIAN) { + // RGBA to ARGB + return ((color & 0xFFFFFF00) >>> 8) | ((color & 0x000000FF) << 24); + } else { + // ABGR to ARGB + return (color & 0xFF00FF00) | ((color & 0x00FF0000) >>> 16) | ((color & 0x000000FF) << 16); + } + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/pipeline/helper/GeometryHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/helper/GeometryHelper.java new file mode 100644 index 000000000..f638d4e17 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/helper/GeometryHelper.java @@ -0,0 +1,243 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.pipeline.helper; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.Direction; +import net.minecraft.core.Direction.Axis; +import net.minecraft.core.Direction.AxisDirection; +import net.vulkanmod.render.quad.QuadView; +import org.joml.Vector3f; + +import static net.minecraft.util.Mth.equal; + +/** + * Static routines of general utility for renderer implementations. + * Renderers are not required to use these helpers, but they were + * designed to be usable without the default renderer. + */ +public abstract class GeometryHelper { + /** + * set when a quad touches all four corners of a unit cube. + */ + public static final int CUBIC_FLAG = 1; + /** + * set when a quad is parallel to (but not necessarily on) a its light face. + */ + public static final int AXIS_ALIGNED_FLAG = CUBIC_FLAG << 1; + /** + * set when a quad is coplanar with its light face. Implies {@link #AXIS_ALIGNED_FLAG} + */ + public static final int LIGHT_FACE_FLAG = AXIS_ALIGNED_FLAG << 1; + /** + * how many bits quad header encoding should reserve for encoding geometry flags. + */ + public static final int FLAG_BIT_COUNT = 3; + private static final float EPS_MIN = 0.0001f; + private static final float EPS_MAX = 1.0f - EPS_MIN; + private GeometryHelper() { + } + + /** + * Analyzes the quad and returns a value with some combination + * of {@link #AXIS_ALIGNED_FLAG}, {@link #LIGHT_FACE_FLAG} and {@link #CUBIC_FLAG}. + * Intended use is to optimize lighting when the geometry is regular. + * Expects convex quads with all points co-planar. + */ + public static int computeShapeFlags(QuadView quad) { + Direction lightFace = quad.lightFace(); + int bits = 0; + + if (isQuadParallelToFace(lightFace, quad)) { + bits |= AXIS_ALIGNED_FLAG; + + if (isParallelQuadOnFace(lightFace, quad)) { + bits |= LIGHT_FACE_FLAG; + } + } + + if (isQuadCubic(lightFace, quad)) { + bits |= CUBIC_FLAG; + } + + return bits; + } + + /** + * Returns true if quad is parallel to the given face. + * Does not validate quad winding order. + * Expects convex quads with all points co-planar. + */ + public static boolean isQuadParallelToFace(Direction face, QuadView quad) { + int i = face.getAxis().ordinal(); + final float val = quad.posByIndex(0, i); + return equal(val, quad.posByIndex(1, i)) && equal(val, quad.posByIndex(2, i)) && equal(val, quad.posByIndex(3, i)); + } + + /** + * True if quad - already known to be parallel to a face - is actually coplanar with it. + * For compatibility with vanilla resource packs, also true if quad is outside the face. + * + *

Test will be unreliable if not already parallel, use {@link #isQuadParallelToFace(Direction, QuadView)} + * for that purpose. Expects convex quads with all points co-planar. + */ + public static boolean isParallelQuadOnFace(Direction lightFace, QuadView quad) { + final float x = quad.posByIndex(0, lightFace.getAxis().ordinal()); + return lightFace.getAxisDirection() == AxisDirection.POSITIVE ? x >= EPS_MAX : x <= EPS_MIN; + } + + /** + * Returns true if quad is truly a quad (not a triangle) and fills a full block cross-section. + * If known to be true, allows use of a simpler/faster AO lighting algorithm. + * + *

Does not check if quad is actually coplanar with the light face, nor does it check that all + * quad vertices are coplanar with each other. + * + *

Expects convex quads with all points co-planar. + */ + public static boolean isQuadCubic(Direction lightFace, QuadView quad) { + int a, b; + + switch (lightFace) { + case EAST: + case WEST: + a = 1; + b = 2; + break; + case UP: + case DOWN: + a = 0; + b = 2; + break; + case SOUTH: + case NORTH: + a = 1; + b = 0; + break; + default: + // handle WTF case + return false; + } + + return confirmSquareCorners(a, b, quad); + } + + /** + * Used by {@link #isQuadCubic(Direction, QuadView)}. + * True if quad touches all four corners of unit square. + * + *

For compatibility with resource packs that contain models with quads exceeding + * block boundaries, considers corners outside the block to be at the corners. + */ + private static boolean confirmSquareCorners(int aCoordinate, int bCoordinate, QuadView quad) { + int flags = 0; + + for (int i = 0; i < 4; i++) { + final float a = quad.posByIndex(i, aCoordinate); + final float b = quad.posByIndex(i, bCoordinate); + + if (a <= EPS_MIN) { + if (b <= EPS_MIN) { + flags |= 1; + } else if (b >= EPS_MAX) { + flags |= 2; + } else { + return false; + } + } else if (a >= EPS_MAX) { + if (b <= EPS_MIN) { + flags |= 4; + } else if (b >= EPS_MAX) { + flags |= 8; + } else { + return false; + } + } else { + return false; + } + } + + return flags == 15; + } + + /** + * Identifies the face to which the quad is most closely aligned. + * This mimics the value that {@link BakedQuad#getDirection()} returns, and is + * used in the vanilla renderer for all diffuse lighting. + * + *

Derived from the quad face normal and expects convex quads with all points co-planar. + */ + public static Direction lightFace(QuadView quad) { + final Vector3f normal = quad.faceNormal(); + switch (GeometryHelper.longestAxis(normal)) { + case X: + return normal.x() > 0 ? Direction.EAST : Direction.WEST; + + case Y: + return normal.y() > 0 ? Direction.UP : Direction.DOWN; + + case Z: + return normal.z() > 0 ? Direction.SOUTH : Direction.NORTH; + + default: + // handle WTF case + return Direction.UP; + } + } + + /** + * Simple 4-way compare, doesn't handle NaN values. + */ + public static float min(float a, float b, float c, float d) { + final float x = a < b ? a : b; + final float y = c < d ? c : d; + return x < y ? x : y; + } + + /** + * Simple 4-way compare, doesn't handle NaN values. + */ + public static float max(float a, float b, float c, float d) { + final float x = a > b ? a : b; + final float y = c > d ? c : d; + return x > y ? x : y; + } + + /** + * @see #longestAxis(float, float, float) + */ + public static Axis longestAxis(Vector3f vec) { + return longestAxis(vec.x(), vec.y(), vec.z()); + } + + /** + * Identifies the largest (max absolute magnitude) component (X, Y, Z) in the given vector. + */ + public static Axis longestAxis(float normalX, float normalY, float normalZ) { + Axis result = Axis.Y; + float longest = Math.abs(normalY); + float a = Math.abs(normalX); + + if (a > longest) { + result = Axis.X; + longest = a; + } + + return Math.abs(normalZ) > longest + ? Axis.Z : result; + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/pipeline/helper/NormalHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/helper/NormalHelper.java new file mode 100644 index 000000000..d8760698b --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/helper/NormalHelper.java @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.pipeline.helper; + +import net.minecraft.core.Direction; +import net.minecraft.util.Mth; +import net.vulkanmod.render.model.quad.ModelQuadView; +import net.vulkanmod.render.quad.QuadView; +import net.vulkanmod.render.vertex.format.I32_SNorm; +import org.jetbrains.annotations.NotNull; +import org.joml.Vector3f; + +/** + * Static routines of general utility for renderer implementations. + * Renderers are not required to use these helpers, but they were + * designed to be usable without the default renderer. + */ +public abstract class NormalHelper { + private static final float PACK = 127.0f; + private static final float UNPACK = 1.0f / PACK; + private NormalHelper() { + } + + /** + * Stores a normal plus an extra value as a quartet of signed bytes. + * This is the same normal format that vanilla rendering expects. + * The extra value is for use by shaders. + */ + public static int packNormal(float x, float y, float z, float w) { + x = Mth.clamp(x, -1, 1); + y = Mth.clamp(y, -1, 1); + z = Mth.clamp(z, -1, 1); + w = Mth.clamp(w, -1, 1); + + return ((int) (x * PACK) & 0xFF) | (((int) (y * PACK) & 0xFF) << 8) | (((int) (z * PACK) & 0xFF) << 16) | (((int) (w * PACK) & 0xFF) << 24); + } + + /** + * Version of {@link #packNormal(float, float, float, float)} that accepts a vector type. + */ + public static int packNormal(Vector3f normal, float w) { + return packNormal(normal.x(), normal.y(), normal.z(), w); + } + + /** + * Like {@link #packNormal(float, float, float, float)}, but without a {@code w} value. + */ + public static int packNormal(float x, float y, float z) { + x = Mth.clamp(x, -1, 1); + y = Mth.clamp(y, -1, 1); + z = Mth.clamp(z, -1, 1); + + return ((int) (x * PACK) & 0xFF) | (((int) (y * PACK) & 0xFF) << 8) | (((int) (z * PACK) & 0xFF) << 16); + } + + /** + * Like {@link #packNormal(Vector3f, float)}, but without a {@code w} value. + */ + public static int packNormal(Vector3f normal) { + return packNormal(normal.x(), normal.y(), normal.z()); + } + + public static float unpackNormalX(int packedNormal) { + return ((byte) (packedNormal & 0xFF)) * UNPACK; + } + + public static float unpackNormalY(int packedNormal) { + return ((byte) ((packedNormal >>> 8) & 0xFF)) * UNPACK; + } + + public static float unpackNormalZ(int packedNormal) { + return ((byte) ((packedNormal >>> 16) & 0xFF)) * UNPACK; + } + + public static float unpackNormalW(int packedNormal) { + return ((byte) ((packedNormal >>> 24) & 0xFF)) * UNPACK; + } + + public static void unpackNormal(int packedNormal, Vector3f target) { + target.set(unpackNormalX(packedNormal), unpackNormalY(packedNormal), unpackNormalZ(packedNormal)); + } + + /** + * Computes the face normal of the given quad and saves it in the provided non-null vector. + * If {@link QuadView#nominalFace()} is set will optimize by confirming quad is parallel to that + * face and, if so, use the standard normal for that face direction. + * + *

Will work with triangles also. Assumes counter-clockwise winding order, which is the norm. + * Expects convex quads with all points co-planar. + */ + public static void computeFaceNormal(@NotNull Vector3f saveTo, QuadView q) { + final Direction nominalFace = q.nominalFace(); + + if (nominalFace != null && GeometryHelper.isQuadParallelToFace(nominalFace, q)) { + saveTo.set(nominalFace.getStepX(), nominalFace.getStepY(), nominalFace.getStepZ()); + return; + } + + final float x0 = q.x(0); + final float y0 = q.y(0); + final float z0 = q.z(0); + final float x1 = q.x(1); + final float y1 = q.y(1); + final float z1 = q.z(1); + final float x2 = q.x(2); + final float y2 = q.y(2); + final float z2 = q.z(2); + final float x3 = q.x(3); + final float y3 = q.y(3); + final float z3 = q.z(3); + + final float dx0 = x2 - x0; + final float dy0 = y2 - y0; + final float dz0 = z2 - z0; + final float dx1 = x3 - x1; + final float dy1 = y3 - y1; + final float dz1 = z3 - z1; + + float normX = dy0 * dz1 - dz0 * dy1; + float normY = dz0 * dx1 - dx0 * dz1; + float normZ = dx0 * dy1 - dy0 * dx1; + + float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ); + + if (l != 0) { + normX /= l; + normY /= l; + normZ /= l; + } + + saveTo.set(normX, normY, normZ); + } + + public static int computePackedNormal(ModelQuadView q) { + final float x0 = q.getX(0); + final float y0 = q.getY(0); + final float z0 = q.getZ(0); + final float x1 = q.getX(1); + final float y1 = q.getY(1); + final float z1 = q.getZ(1); + final float x2 = q.getX(2); + final float y2 = q.getY(2); + final float z2 = q.getZ(2); + final float x3 = q.getX(3); + final float y3 = q.getY(3); + final float z3 = q.getZ(3); + + final float dx0 = x2 - x0; + final float dy0 = y2 - y0; + final float dz0 = z2 - z0; + final float dx1 = x3 - x1; + final float dy1 = y3 - y1; + final float dz1 = z3 - z1; + + float normX = dy0 * dz1 - dz0 * dy1; + float normY = dz0 * dx1 - dx0 * dz1; + float normZ = dx0 * dy1 - dy0 * dx1; + + float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ); + + if (l != 0) { + normX /= l; + normY /= l; + normZ /= l; + } + + return I32_SNorm.packNormal(normX, normY, normZ); + } + + public static int packedNormalFromDirection(Direction direction) { + return I32_SNorm.packNormal(direction.getStepX(), direction.getStepY(), direction.getStepZ()); + } + + public static void unpackNormalTo(int packedNormal, Vector3f normal) { + normal.set(I32_SNorm.unpackX(packedNormal), I32_SNorm.unpackY(packedNormal), I32_SNorm.unpackZ(packedNormal)); + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/pipeline/helper/TextureHelper.java b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/helper/TextureHelper.java new file mode 100644 index 000000000..d14206a56 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/helper/TextureHelper.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.pipeline.helper; + +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.core.Direction; +import net.vulkanmod.render.quad.MutableQuadView; + +/** + * Handles most texture-baking use cases for model loaders and model libraries + * via {@link #bakeSprite(MutableQuadView, TextureAtlasSprite, int)}. Also used by the API + * itself to implement automatic block-breaking models for enhanced models. + */ +public class TextureHelper { + private static final float NORMALIZER = 1f / 16f; + private static final VertexModifier[] ROTATIONS = new VertexModifier[]{ + null, + (q, i) -> q.uv(i, q.v(i), 1 - q.u(i)), //90 + (q, i) -> q.uv(i, 1 - q.u(i), 1 - q.v(i)), //180 + (q, i) -> q.uv(i, 1 - q.v(i), q.u(i)) // 270 + }; + private static final VertexModifier[] UVLOCKERS = new VertexModifier[6]; + + static { + UVLOCKERS[Direction.EAST.get3DDataValue()] = (q, i) -> q.uv(i, 1 - q.z(i), 1 - q.y(i)); + UVLOCKERS[Direction.WEST.get3DDataValue()] = (q, i) -> q.uv(i, q.z(i), 1 - q.y(i)); + UVLOCKERS[Direction.NORTH.get3DDataValue()] = (q, i) -> q.uv(i, 1 - q.x(i), 1 - q.y(i)); + UVLOCKERS[Direction.SOUTH.get3DDataValue()] = (q, i) -> q.uv(i, q.x(i), 1 - q.y(i)); + UVLOCKERS[Direction.DOWN.get3DDataValue()] = (q, i) -> q.uv(i, q.x(i), 1 - q.z(i)); + UVLOCKERS[Direction.UP.get3DDataValue()] = (q, i) -> q.uv(i, q.x(i), q.z(i)); + } + + private TextureHelper() { + } + + /** + * Bakes textures in the provided vertex data, handling UV locking, + * rotation, interpolation, etc. Textures must not be already baked. + */ + public static void bakeSprite(MutableQuadView quad, TextureAtlasSprite sprite, int bakeFlags) { + if (quad.nominalFace() != null && (MutableQuadView.BAKE_LOCK_UV & bakeFlags) != 0) { + // Assigns normalized UV coordinates based on vertex positions + applyModifier(quad, UVLOCKERS[quad.nominalFace().get3DDataValue()]); + } else if ((MutableQuadView.BAKE_NORMALIZED & bakeFlags) == 0) { // flag is NOT set, UVs are assumed to not be normalized yet as is the default, normalize through dividing by 16 + // Scales from 0-16 to 0-1 + applyModifier(quad, (q, i) -> q.uv(i, q.u(i) * NORMALIZER, q.v(i) * NORMALIZER)); + } + + final int rotation = bakeFlags & 3; + + if (rotation != 0) { + // Rotates texture around the center of sprite. + // Assumes normalized coordinates. + applyModifier(quad, ROTATIONS[rotation]); + } + + if ((MutableQuadView.BAKE_FLIP_U & bakeFlags) != 0) { + // Inverts U coordinates. Assumes normalized (0-1) values. + applyModifier(quad, (q, i) -> q.uv(i, 1 - q.u(i), q.v(i))); + } + + if ((MutableQuadView.BAKE_FLIP_V & bakeFlags) != 0) { + // Inverts V coordinates. Assumes normalized (0-1) values. + applyModifier(quad, (q, i) -> q.uv(i, q.u(i), 1 - q.v(i))); + } + + interpolate(quad, sprite); + } + + /** + * Faster than sprite method. Sprite computes span and normalizes inputs each call, + * so we'd have to denormalize before we called, only to have the sprite renormalize immediately. + */ + private static void interpolate(MutableQuadView q, TextureAtlasSprite sprite) { + final float uMin = sprite.getU0(); + final float uSpan = sprite.getU1() - uMin; + final float vMin = sprite.getV0(); + final float vSpan = sprite.getV1() - vMin; + + for (int i = 0; i < 4; i++) { + q.uv(i, uMin + q.u(i) * uSpan, vMin + q.v(i) * vSpan); + } + } + + private static void applyModifier(MutableQuadView quad, VertexModifier modifier) { + for (int i = 0; i < 4; i++) { + modifier.apply(quad, i); + } + } + + @FunctionalInterface + private interface VertexModifier { + void apply(MutableQuadView quad, int vertexIndex); + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/pipeline/mesh/EncodingFormat.java b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/mesh/EncodingFormat.java new file mode 100644 index 000000000..917c41890 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/mesh/EncodingFormat.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.pipeline.mesh; + +import com.google.common.base.Preconditions; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.core.Direction; +import net.minecraft.util.Mth; +import net.vulkanmod.render.chunk.build.pipeline.helper.GeometryHelper; +import net.vulkanmod.render.material.RenderMaterial; +import net.vulkanmod.render.material.RenderMaterialRegistry; +import net.vulkanmod.render.model.ModelHelper; +import net.vulkanmod.render.quad.QuadView; +import org.jetbrains.annotations.Nullable; + +/** + * Holds all the array offsets and bit-wise encoders/decoders for + * packing/unpacking quad data in an array of integers. + * All of this is implementation-specific - that's why it isn't a "helper" class. + */ +public abstract class EncodingFormat { + public static final int HEADER_STRIDE = 4; + public static final int VERTEX_STRIDE; + public static final int QUAD_STRIDE; + public static final int QUAD_STRIDE_BYTES; + public static final int TOTAL_STRIDE; + static final int HEADER_BITS = 0; + static final int HEADER_FACE_NORMAL = 1; + static final int HEADER_COLOR_INDEX = 2; + static final int HEADER_TAG = 3; + static final int VERTEX_X; + static final int VERTEX_Y; + static final int VERTEX_Z; + static final int VERTEX_COLOR; + static final int VERTEX_U; + static final int VERTEX_V; + static final int VERTEX_LIGHTMAP; + static final int VERTEX_NORMAL; + /** + * used for quick clearing of quad buffers. + */ + static final int[] EMPTY; + private static final int DIRECTION_COUNT = Direction.values().length; + private static final int NULLABLE_DIRECTION_COUNT = DIRECTION_COUNT + 1; + private static final int CULL_BIT_LENGTH = Mth.ceillog2(NULLABLE_DIRECTION_COUNT); + private static final int LIGHT_BIT_OFFSET = CULL_BIT_OFFSET + CULL_BIT_LENGTH; + private static final int CULL_MASK = bitMask(CULL_BIT_LENGTH, CULL_BIT_OFFSET); + private static final int NORMALS_BIT_LENGTH = 4; + private static final int GEOMETRY_BIT_LENGTH = GeometryHelper.FLAG_BIT_COUNT; + private static final int MATERIAL_BIT_LENGTH = 12; + private static final int CULL_BIT_OFFSET = 0; + private static final int LIGHT_BIT_LENGTH = Mth.ceillog2(DIRECTION_COUNT); + private static final int NORMALS_BIT_OFFSET = LIGHT_BIT_OFFSET + LIGHT_BIT_LENGTH; + private static final int GEOMETRY_BIT_OFFSET = NORMALS_BIT_OFFSET + NORMALS_BIT_LENGTH; + private static final int MATERIAL_BIT_OFFSET = GEOMETRY_BIT_OFFSET + GEOMETRY_BIT_LENGTH; + private static final int TOTAL_BIT_LENGTH = MATERIAL_BIT_OFFSET + MATERIAL_BIT_LENGTH; + private static final int MATERIAL_MASK = bitMask(MATERIAL_BIT_LENGTH, MATERIAL_BIT_OFFSET); + private static final int GEOMETRY_MASK = bitMask(GEOMETRY_BIT_LENGTH, GEOMETRY_BIT_OFFSET); + private static final int NORMALS_MASK = bitMask(NORMALS_BIT_LENGTH, NORMALS_BIT_OFFSET); + private static final int LIGHT_MASK = bitMask(LIGHT_BIT_LENGTH, LIGHT_BIT_OFFSET); + + static { + final VertexFormat format = DefaultVertexFormat.BLOCK; + VERTEX_X = HEADER_STRIDE; + VERTEX_Y = HEADER_STRIDE + 1; + VERTEX_Z = HEADER_STRIDE + 2; + VERTEX_COLOR = HEADER_STRIDE + 3; + VERTEX_U = HEADER_STRIDE + 4; + VERTEX_V = VERTEX_U + 1; + VERTEX_LIGHTMAP = HEADER_STRIDE + 6; + VERTEX_NORMAL = HEADER_STRIDE + 7; + VERTEX_STRIDE = format.getVertexSize() / 4; + QUAD_STRIDE = VERTEX_STRIDE * 4; + QUAD_STRIDE_BYTES = QUAD_STRIDE * 4; + TOTAL_STRIDE = HEADER_STRIDE + QUAD_STRIDE; + EMPTY = new int[TOTAL_STRIDE]; + + Preconditions.checkState(VERTEX_STRIDE == QuadView.VANILLA_VERTEX_STRIDE, "Indigo vertex stride (%s) mismatched with rendering API (%s)", VERTEX_STRIDE, QuadView.VANILLA_VERTEX_STRIDE); + Preconditions.checkState(QUAD_STRIDE == QuadView.VANILLA_QUAD_STRIDE, "Indigo quad stride (%s) mismatched with rendering API (%s)", QUAD_STRIDE, QuadView.VANILLA_QUAD_STRIDE); + } + + static { + Preconditions.checkArgument(TOTAL_BIT_LENGTH <= 32, "Indigo header encoding bit count (%s) exceeds integer bit length)", TOTAL_STRIDE); + } + + private EncodingFormat() { + } + + public static int bitMask(int bitLength, int bitOffset) { + return ((1 << bitLength) - 1) << bitOffset; + } + + @Nullable + static Direction cullFace(int bits) { + return ModelHelper.faceFromIndex((bits & CULL_MASK) >>> CULL_BIT_OFFSET); + } + + static int cullFace(int bits, @Nullable Direction face) { + return (bits & ~CULL_MASK) | (ModelHelper.toFaceIndex(face) << CULL_BIT_OFFSET); + } + + static Direction lightFace(int bits) { + return ModelHelper.faceFromIndex((bits & LIGHT_MASK) >>> LIGHT_BIT_OFFSET); + } + + static int lightFace(int bits, Direction face) { + return (bits & ~LIGHT_MASK) | (ModelHelper.toFaceIndex(face) << LIGHT_BIT_OFFSET); + } + + /** + * indicate if vertex normal has been set - bits correspond to vertex ordinals. + */ + static int normalFlags(int bits) { + return (bits & NORMALS_MASK) >>> NORMALS_BIT_OFFSET; + } + + static int normalFlags(int bits, int normalFlags) { + return (bits & ~NORMALS_MASK) | ((normalFlags << NORMALS_BIT_OFFSET) & NORMALS_MASK); + } + + static int geometryFlags(int bits) { + return (bits & GEOMETRY_MASK) >>> GEOMETRY_BIT_OFFSET; + } + + static int geometryFlags(int bits, int geometryFlags) { + return (bits & ~GEOMETRY_MASK) | ((geometryFlags << GEOMETRY_BIT_OFFSET) & GEOMETRY_MASK); + } + + static RenderMaterial material(int bits) { + int id = (bits & MATERIAL_MASK) >>> MATERIAL_BIT_OFFSET; + return RenderMaterialRegistry.fromId(id); + } + + static int material(int bits, RenderMaterial material) { + int id = RenderMaterialRegistry.getId(material); + return (bits & ~MATERIAL_MASK) | ((id << MATERIAL_BIT_OFFSET) & MATERIAL_MASK); + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/pipeline/mesh/MutableQuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/mesh/MutableQuadViewImpl.java new file mode 100644 index 000000000..89ac5114e --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/mesh/MutableQuadViewImpl.java @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.pipeline.mesh; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.core.Direction; +import net.vulkanmod.render.chunk.build.pipeline.helper.ColorHelper; +import net.vulkanmod.render.chunk.build.pipeline.helper.NormalHelper; +import net.vulkanmod.render.chunk.build.pipeline.helper.TextureHelper; +import net.vulkanmod.render.material.RenderMaterial; +import net.vulkanmod.render.material.RenderMaterialRegistry; +import net.vulkanmod.render.model.quad.ModelQuadView; +import net.vulkanmod.render.quad.MutableQuadView; +import net.vulkanmod.render.quad.QuadView; +import org.jetbrains.annotations.Nullable; + +import static net.vulkanmod.render.chunk.build.pipeline.mesh.EncodingFormat.*; + +/** + * Almost-concrete implementation of a mutable quad. The only missing part is {@link #emitDirectly()}, + * because that depends on where/how it is used. (Mesh encoding vs. render-time transformation). + * + *

In many cases an instance of this class is used as an "editor quad". The editor quad's + * {@link #emitDirectly()} method calls some other internal method that transforms the quad + * data and then buffers it. Transformations should be the same as they would be in a vanilla + * render - the editor is serving mainly as a way to access vertex data without magical + * numbers. It also allows for a consistent interface for those transformations. + */ +public abstract class MutableQuadViewImpl extends QuadViewImpl implements MutableQuadView { + public void clear() { + System.arraycopy(EMPTY, 0, data, baseIndex, EncodingFormat.TOTAL_STRIDE); + isGeometryInvalid = true; + nominalFace = null; + normalFlags(0); + tag(0); + colorIndex(-1); + cullFace(null); + material(RenderMaterialRegistry.STANDARD_MATERIAL); + } + + @Override + public MutableQuadViewImpl pos(int vertexIndex, float x, float y, float z) { + final int index = baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_X; + data[index] = Float.floatToRawIntBits(x); + data[index + 1] = Float.floatToRawIntBits(y); + data[index + 2] = Float.floatToRawIntBits(z); + isGeometryInvalid = true; + return this; + } + + @Override + public MutableQuadViewImpl color(int vertexIndex, int color) { + data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_COLOR] = color; + return this; + } + + @Override + public MutableQuadViewImpl uv(int vertexIndex, float u, float v) { + final int i = baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_U; + data[i] = Float.floatToRawIntBits(u); + data[i + 1] = Float.floatToRawIntBits(v); + return this; + } + + @Override + public MutableQuadViewImpl spriteBake(TextureAtlasSprite sprite, int bakeFlags) { + TextureHelper.bakeSprite(this, sprite, bakeFlags); + return this; + } + + @Override + public MutableQuadViewImpl lightmap(int vertexIndex, int lightmap) { + data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_LIGHTMAP] = lightmap; + return this; + } + + protected void normalFlags(int flags) { + data[baseIndex + HEADER_BITS] = EncodingFormat.normalFlags(data[baseIndex + HEADER_BITS], flags); + } + + @Override + public MutableQuadViewImpl normal(int vertexIndex, float x, float y, float z) { + normalFlags(normalFlags() | (1 << vertexIndex)); + data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_NORMAL] = NormalHelper.packNormal(x, y, z); + return this; + } + + /** + * Internal helper method. Copies face normals to vertex normals lacking one. + */ + public final void populateMissingNormals() { + final int normalFlags = this.normalFlags(); + + if (normalFlags == 0b1111) return; + + final int packedFaceNormal = packedFaceNormal(); + + for (int v = 0; v < 4; v++) { + if ((normalFlags & (1 << v)) == 0) { + data[baseIndex + v * VERTEX_STRIDE + VERTEX_NORMAL] = packedFaceNormal; + } + } + + normalFlags(0b1111); + } + + @Override + public final MutableQuadViewImpl cullFace(@Nullable Direction face) { + data[baseIndex + HEADER_BITS] = EncodingFormat.cullFace(data[baseIndex + HEADER_BITS], face); + nominalFace(face); + return this; + } + + @Override + public final MutableQuadViewImpl nominalFace(@Nullable Direction face) { + nominalFace = face; + return this; + } + + @Override + public final MutableQuadViewImpl material(RenderMaterial material) { + if (material == null) { + material = RenderMaterialRegistry.STANDARD_MATERIAL; + } + + data[baseIndex + HEADER_BITS] = EncodingFormat.material(data[baseIndex + HEADER_BITS], material); + return this; + } + + @Override + public final MutableQuadViewImpl colorIndex(int colorIndex) { + data[baseIndex + HEADER_COLOR_INDEX] = colorIndex; + return this; + } + + @Override + public final MutableQuadViewImpl tag(int tag) { + data[baseIndex + HEADER_TAG] = tag; + return this; + } + + @Override + public MutableQuadViewImpl copyFrom(QuadView quad) { + final QuadViewImpl q = (QuadViewImpl) quad; + q.computeGeometry(); + + System.arraycopy(q.data, q.baseIndex, data, baseIndex, EncodingFormat.TOTAL_STRIDE); + faceNormal.set(q.faceNormal); + nominalFace = q.nominalFace; + isGeometryInvalid = false; + return this; + } + + @Override + public final MutableQuadViewImpl fromVanilla(int[] quadData, int startIndex) { + System.arraycopy(quadData, startIndex, data, baseIndex + HEADER_STRIDE, VANILLA_QUAD_STRIDE); + isGeometryInvalid = true; + + int colorIndex = baseIndex + VERTEX_COLOR; + + for (int i = 0; i < 4; i++) { + data[colorIndex] = ColorHelper.fromVanillaColor(data[colorIndex]); + colorIndex += VERTEX_STRIDE; + } + + return this; + } + + @Override + public final MutableQuadViewImpl fromVanilla(BakedQuad quad, RenderMaterial material, @Nullable Direction cullFace) { + fromVanilla(quad.vertices(), 0); + data[baseIndex + HEADER_BITS] = EncodingFormat.cullFace(0, cullFace); + nominalFace(quad.direction()); + colorIndex(quad.tintIndex()); + + if (!quad.shade()) { + material = RenderMaterialRegistry.disableDiffuse(material, true); + } + + material(material); + tag(0); + + // Copy data from BakedQuad instead of calculating properties + ModelQuadView quadView = (ModelQuadView) (Object) quad; + int normal = quadView.getNormal(); + data[baseIndex + HEADER_FACE_NORMAL] = normal; + NormalHelper.unpackNormalTo(normal, faceNormal); + + Direction lightFace = quadView.lightFace(); + data[baseIndex + HEADER_BITS] = EncodingFormat.lightFace(data[baseIndex + HEADER_BITS], lightFace); + data[baseIndex + HEADER_BITS] = EncodingFormat.geometryFlags(data[baseIndex + HEADER_BITS], quadView.getFlags()); + + this.facing = quadView.getQuadFacing(); + + this.isGeometryInvalid = false; + return this; + } + + /** + * Emit the quad without clearing the underlying data. + * Geometry is not guaranteed to be valid when called, but can be computed by calling {@link #computeGeometry()}. + */ + public abstract void emitDirectly(); + + @Override + public final MutableQuadViewImpl emit() { + emitDirectly(); + clear(); + return this; + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/pipeline/mesh/QuadViewImpl.java b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/mesh/QuadViewImpl.java new file mode 100644 index 000000000..279a6afe0 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/chunk/build/pipeline/mesh/QuadViewImpl.java @@ -0,0 +1,334 @@ +/* + * Copyright (c) 2016, 2017, 2018, 2019 FabricMC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.vulkanmod.render.chunk.build.pipeline.mesh; + +import net.minecraft.core.Direction; +import net.vulkanmod.render.chunk.build.pipeline.helper.ColorHelper; +import net.vulkanmod.render.chunk.build.pipeline.helper.GeometryHelper; +import net.vulkanmod.render.chunk.build.pipeline.helper.NormalHelper; +import net.vulkanmod.render.chunk.cull.QuadFacing; +import net.vulkanmod.render.material.RenderMaterial; +import net.vulkanmod.render.model.quad.ModelQuadFlags; +import net.vulkanmod.render.model.quad.ModelQuadView; +import net.vulkanmod.render.quad.QuadView; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector2f; +import org.joml.Vector3f; + +import static net.vulkanmod.render.chunk.build.pipeline.mesh.EncodingFormat.*; + +/** + * Base class for all quads / quad makers. Handles the ugly bits + * of maintaining and encoding the quad state. + */ +public class QuadViewImpl implements QuadView, ModelQuadView { + protected final Vector3f faceNormal = new Vector3f(); + @Nullable + protected Direction nominalFace; + /** + * True when face normal, light face, or geometry flags may not match geometry. + */ + protected boolean isGeometryInvalid = true; + /** + * Size and where it comes from will vary in subtypes. But in all cases quad is fully encoded to array. + */ + protected int[] data; + + /** + * Beginning of the quad. Also the header index. + */ + protected int baseIndex = 0; + + protected QuadFacing facing; + + /** + * Decodes necessary state from the backing data array. + * The encoded data must contain valid computed geometry. + */ + public void load() { + isGeometryInvalid = false; + nominalFace = lightFace(); + NormalHelper.unpackNormal(packedFaceNormal(), faceNormal); + facing = QuadFacing.fromNormal(faceNormal); + } + + protected void computeGeometry() { + if (isGeometryInvalid) { + isGeometryInvalid = false; + + NormalHelper.computeFaceNormal(faceNormal, this); + data[baseIndex + HEADER_FACE_NORMAL] = NormalHelper.packNormal(faceNormal); + + // depends on face normal + Direction lightFace = GeometryHelper.lightFace(this); + data[baseIndex + HEADER_BITS] = EncodingFormat.lightFace(data[baseIndex + HEADER_BITS], lightFace); + + // depends on light face + data[baseIndex + HEADER_BITS] = EncodingFormat.geometryFlags(data[baseIndex + HEADER_BITS], ModelQuadFlags.getQuadFlags(this, lightFace)); + + facing = QuadFacing.fromNormal(faceNormal); + } + } + + /** + * gets flags used for lighting - lazily computed via {@link GeometryHelper#computeShapeFlags(QuadView)}. + */ + public int geometryFlags() { + computeGeometry(); + return EncodingFormat.geometryFlags(data[baseIndex + HEADER_BITS]); + } + + public boolean hasShade() { + return !material().disableDiffuse(); + } + + @Override + public float x(int vertexIndex) { + return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_X]); + } + + @Override + public float y(int vertexIndex) { + return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_Y]); + } + + @Override + public float z(int vertexIndex) { + return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_Z]); + } + + @Override + public float posByIndex(int vertexIndex, int coordinateIndex) { + return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_X + coordinateIndex]); + } + + @Override + public Vector3f copyPos(int vertexIndex, @Nullable Vector3f target) { + if (target == null) { + target = new Vector3f(); + } + + final int index = baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_X; + target.set(Float.intBitsToFloat(data[index]), Float.intBitsToFloat(data[index + 1]), Float.intBitsToFloat(data[index + 2])); + return target; + } + + @Override + public int color(int vertexIndex) { + return data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_COLOR]; + } + + @Override + public float u(int vertexIndex) { + return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_U]); + } + + @Override + public float v(int vertexIndex) { + return Float.intBitsToFloat(data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_V]); + } + + @Override + public Vector2f copyUv(int vertexIndex, @Nullable Vector2f target) { + if (target == null) { + target = new Vector2f(); + } + + final int index = baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_U; + target.set(Float.intBitsToFloat(data[index]), Float.intBitsToFloat(data[index + 1])); + return target; + } + + @Override + public int lightmap(int vertexIndex) { + return data[baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_LIGHTMAP]; + } + + public int normalFlags() { + return EncodingFormat.normalFlags(data[baseIndex + HEADER_BITS]); + } + + @Override + public boolean hasNormal(int vertexIndex) { + return (normalFlags() & (1 << vertexIndex)) != 0; + } + + /** + * True if any vertex normal has been set. + */ + public boolean hasVertexNormals() { + return normalFlags() != 0; + } + + /** + * True if all vertex normals have been set. + */ + public boolean hasAllVertexNormals() { + return (normalFlags() & 0b1111) == 0b1111; + } + + protected final int normalIndex(int vertexIndex) { + return baseIndex + vertexIndex * VERTEX_STRIDE + VERTEX_NORMAL; + } + + @Override + public float normalX(int vertexIndex) { + return hasNormal(vertexIndex) ? NormalHelper.unpackNormalX(data[normalIndex(vertexIndex)]) : Float.NaN; + } + + @Override + public float normalY(int vertexIndex) { + return hasNormal(vertexIndex) ? NormalHelper.unpackNormalY(data[normalIndex(vertexIndex)]) : Float.NaN; + } + + @Override + public float normalZ(int vertexIndex) { + return hasNormal(vertexIndex) ? NormalHelper.unpackNormalZ(data[normalIndex(vertexIndex)]) : Float.NaN; + } + + @Override + @Nullable + public Vector3f copyNormal(int vertexIndex, @Nullable Vector3f target) { + if (hasNormal(vertexIndex)) { + if (target == null) { + target = new Vector3f(); + } + + final int normal = data[normalIndex(vertexIndex)]; + NormalHelper.unpackNormal(normal, target); + return target; + } else { + return null; + } + } + + @Override + @Nullable + public final Direction cullFace() { + return EncodingFormat.cullFace(data[baseIndex + HEADER_BITS]); + } + + @Override + @NotNull + public final Direction lightFace() { + computeGeometry(); + return EncodingFormat.lightFace(data[baseIndex + HEADER_BITS]); + } + + @Override + @Nullable + public final Direction nominalFace() { + return nominalFace; + } + + public final int packedFaceNormal() { + computeGeometry(); + return data[baseIndex + HEADER_FACE_NORMAL]; + } + + @Override + public final Vector3f faceNormal() { + computeGeometry(); + return faceNormal; + } + + @Override + public final RenderMaterial material() { + return EncodingFormat.material(data[baseIndex + HEADER_BITS]); + } + + @Override + public final int colorIndex() { + return data[baseIndex + HEADER_COLOR_INDEX]; + } + + @Override + public final int tag() { + return data[baseIndex + HEADER_TAG]; + } + + @Override + public final void toVanilla(int[] target, int targetIndex) { + System.arraycopy(data, baseIndex + HEADER_STRIDE, target, targetIndex, QUAD_STRIDE); + + // The color is the fourth integer in each vertex. + // EncodingFormat.VERTEX_COLOR is not used because it also + // contains the header size; vanilla quads do not have a header. + int colorIndex = targetIndex + 3; + + for (int i = 0; i < 4; i++) { + target[colorIndex] = ColorHelper.toVanillaColor(target[colorIndex]); + colorIndex += VANILLA_VERTEX_STRIDE; + } + } + + @Override + public int getFlags() { + return geometryFlags(); + } + + @Override + public float getX(int idx) { + return this.x(idx); + } + + @Override + public float getY(int idx) { + return this.y(idx); + } + + @Override + public float getZ(int idx) { + return this.z(idx); + } + + @Override + public int getColor(int idx) { + return this.color(idx); + } + + @Override + public float getU(int idx) { + return this.u(idx); + } + + @Override + public float getV(int idx) { + return this.v(idx); + } + + @Override + public int getColorIndex() { + return this.colorIndex(); + } + + @Override + public Direction getFacingDirection() { + return this.lightFace(); + } + + @Override + public int getNormal() { + return packedFaceNormal(); + } + + @Override + public QuadFacing getQuadFacing() { + return this.facing; + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java index f04244f3f..3f8a14ecc 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/BlockRenderer.java @@ -1,124 +1,233 @@ package net.vulkanmod.render.chunk.build.renderer; -import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; -import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; -import net.fabricmc.fabric.api.renderer.v1.material.ShadeMode; -import net.fabricmc.fabric.api.util.TriState; +import it.unimi.dsi.fastutil.objects.Object2ByteLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.client.Minecraft; +import net.minecraft.client.color.block.BlockColor; import net.minecraft.client.renderer.ItemBlockRenderTypes; -import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.renderer.block.BlockRenderDispatcher; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.BlockModelPart; +import net.minecraft.client.renderer.block.model.BlockStateModel; import net.minecraft.core.BlockPos; -import net.minecraft.core.Vec3i; +import net.minecraft.core.Direction; +import net.minecraft.util.RandomSource; import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.SingleThreadedRandomSource; import net.minecraft.world.phys.Vec3; import net.vulkanmod.Initializer; -import net.vulkanmod.render.chunk.build.frapi.mesh.MutableQuadViewImpl; -import net.vulkanmod.render.chunk.build.frapi.render.AbstractBlockRenderContext; +import net.vulkanmod.interfaces.color.BlockColorsExtended; +import net.vulkanmod.render.chunk.build.RenderRegion; import net.vulkanmod.render.chunk.build.light.LightPipeline; import net.vulkanmod.render.chunk.build.light.data.QuadLightData; +import net.vulkanmod.render.chunk.build.pipeline.helper.ColorHelper; +import net.vulkanmod.render.chunk.build.pipeline.mesh.EncodingFormat; +import net.vulkanmod.render.chunk.build.pipeline.mesh.MutableQuadViewImpl; import net.vulkanmod.render.chunk.build.thread.BuilderResources; import net.vulkanmod.render.chunk.cull.QuadFacing; -import net.vulkanmod.render.model.quad.QuadUtils; +import net.vulkanmod.render.material.RenderMaterial; +import net.vulkanmod.render.material.RenderMaterialRegistry; import net.vulkanmod.render.model.quad.ModelQuadView; +import net.vulkanmod.render.model.quad.QuadUtils; import net.vulkanmod.render.vertex.TerrainBufferBuilder; import net.vulkanmod.render.vertex.TerrainBuilder; import net.vulkanmod.render.vertex.TerrainRenderType; import net.vulkanmod.render.vertex.format.I32_SNorm; import net.vulkanmod.vulkan.util.ColorUtil; +import org.jetbrains.annotations.Nullable; import org.joml.Vector3f; -public class BlockRenderer extends AbstractBlockRenderContext { - private Vector3f pos; +import java.util.List; - private BuilderResources resources; - private TerrainBuilder terrainBuilder; +public class BlockRenderer { + private static final Direction[] DIRECTIONS = Direction.values(); - final boolean backFaceCulling = Initializer.CONFIG.backFaceCulling; + private final MutableQuadViewImpl editorQuad = new MutableQuadViewImpl() { + { + data = new int[EncodingFormat.TOTAL_STRIDE]; + clear(); + } + @Override + public void emitDirectly() { + // not used – quads are consumed immediately + } + }; + + private final Object2ByteLinkedOpenHashMap occlusionCache = new Object2ByteLinkedOpenHashMap<>(2048, 0.25F) { + @Override + protected void rehash(int i) { + } + }; + private final OcclusionKey lookupKey = new OcclusionKey(); + + private final RandomSource random = RandomSource.create(); + private final QuadLightData quadLightData = new QuadLightData(); + private final LightPipeline flatLightPipeline; + private final LightPipeline smoothLightPipeline; + private final net.vulkanmod.render.chunk.build.color.BlockColorRegistry blockColorRegistry; + private final boolean backFaceCulling = Initializer.CONFIG.backFaceCulling; + private final BlockPos.MutableBlockPos tempPos = new BlockPos.MutableBlockPos(); + private BuilderResources resources; + private BlockAndTintGetter renderRegion; + private boolean enableCulling = true; + private BlockState blockState; + private BlockPos blockPos; + private boolean useAO; + private long seed; private TerrainRenderType renderType; + private TerrainBuilder terrainBuilder; + private Vector3f currentPos; + private int cullCompletionFlags; + private int cullResultFlags; + + public BlockRenderer(LightPipeline flatLightPipeline, LightPipeline smoothLightPipeline) { + this.flatLightPipeline = flatLightPipeline; + this.smoothLightPipeline = smoothLightPipeline; + this.occlusionCache.defaultReturnValue((byte) 127); + this.blockColorRegistry = BlockColorsExtended.from(Minecraft.getInstance().getBlockColors()).getColorResolverMap(); + } public void setResources(BuilderResources resources) { this.resources = resources; } - public BlockRenderer(LightPipeline flatLightPipeline, LightPipeline smoothLightPipeline) { - super(); - this.setupLightPipelines(flatLightPipeline, smoothLightPipeline); - - this.random = new SingleThreadedRandomSource(42L); + public void prepareForWorld(RenderRegion region, boolean enableCulling) { + this.renderRegion = region; + this.enableCulling = enableCulling; } public void renderBlock(BlockState blockState, BlockPos blockPos, Vector3f pos) { - this.pos = pos; - this.blockPos = blockPos; + if (this.renderRegion == null) { + return; + } + this.blockState = blockState; + this.blockPos = blockPos; + this.currentPos = pos; this.seed = blockState.getSeed(blockPos); + this.random.setSeed(this.seed); + this.useAO = Minecraft.useAmbientOcclusion() && blockState.getLightEmission() == 0; - TerrainRenderType renderType = TerrainRenderType.get(ItemBlockRenderTypes.getChunkRenderType(blockState)); - renderType = TerrainRenderType.getRemapped(renderType); - this.renderType = renderType; - this.terrainBuilder = this.resources.builderPack.builder(renderType); + TerrainRenderType baseType = TerrainRenderType.fromChunkLayer(ItemBlockRenderTypes.getChunkRenderType(blockState)); + baseType = TerrainRenderType.getRemapped(baseType); + this.renderType = baseType; + this.terrainBuilder = this.resources.builderPack.builder(baseType); this.terrainBuilder.setBlockAttributes(blockState); - BakedModel model = Minecraft.getInstance().getBlockRenderer().getBlockModel(blockState); - - BlockAndTintGetter renderRegion = this.renderRegion; - Vec3 offset = blockState.getOffset(renderRegion, blockPos); + BlockAndTintGetter region = this.renderRegion; + Vec3 offset = blockState.getOffset(blockPos); pos.add((float) offset.x, (float) offset.y, (float) offset.z); - this.prepareForBlock(blockState, blockPos, model.useAmbientOcclusion()); + BlockRenderDispatcher dispatcher = Minecraft.getInstance().getBlockRenderer(); + BlockStateModel stateModel = dispatcher.getBlockModel(blockState); + + this.cullCompletionFlags = 0; + this.cullResultFlags = 0; + + List parts = new ObjectArrayList<>(); + stateModel.collectParts(this.random, parts); + + for (BlockModelPart part : parts) { + boolean partUsesAo = part.useAmbientOcclusion(); + RenderMaterial baseMaterial = partUsesAo ? RenderMaterialRegistry.STANDARD_MATERIAL : RenderMaterialRegistry.NO_AO_MATERIAL; + emitQuads(part.getQuads(null), baseMaterial, partUsesAo, null); - model.emitBlockQuads(renderRegion, blockState, blockPos, this.randomSupplier, this); + for (Direction direction : DIRECTIONS) { + if (!shouldRenderFace(direction)) { + continue; + } + + emitQuads(part.getQuads(direction), baseMaterial, partUsesAo, direction); + } + } } - protected void endRenderQuad(MutableQuadViewImpl quad) { - final RenderMaterial mat = quad.material(); - final int colorIndex = mat.disableColorIndex() ? -1 : quad.colorIndex(); - final TriState aoMode = mat.ambientOcclusion(); - final boolean ao = this.useAO && (aoMode == TriState.TRUE || (aoMode == TriState.DEFAULT && this.defaultAO)); - final boolean emissive = mat.emissive(); - final boolean vanillaShade = mat.shadeMode() == ShadeMode.VANILLA; + private void emitQuads(List quads, RenderMaterial baseMaterial, boolean partUsesAo, @Nullable Direction cullFace) { + if (quads == null || quads.isEmpty()) { + return; + } + + for (BakedQuad bakedQuad : quads) { + renderQuad(bakedQuad, baseMaterial, partUsesAo, cullFace); + } + } + + private void renderQuad(BakedQuad bakedQuad, RenderMaterial baseMaterial, boolean partUsesAo, @Nullable Direction cullFace) { + MutableQuadViewImpl quad = this.editorQuad; + quad.clear(); + + RenderMaterial material = bakedQuad.shade() + ? baseMaterial + : RenderMaterialRegistry.disableDiffuse(baseMaterial, true); + + quad.fromVanilla(bakedQuad, material, cullFace); + + colorizeQuad(quad, quad.colorIndex()); + + boolean emissive = bakedQuad.lightEmission() > 0; + boolean applyAo = this.useAO && partUsesAo; + LightPipeline pipeline = applyAo ? this.smoothLightPipeline : this.flatLightPipeline; + + shadeQuad(quad, pipeline, emissive); + copyLightData(quad); + bufferQuad(this.terrainBuilder, this.currentPos, quad, this.quadLightData); + } - TerrainBuilder terrainBuilder = getBufferBuilder(mat.blendMode()); + private void colorizeQuad(MutableQuadViewImpl quad, int colorIndex) { + if (colorIndex == -1) { + return; + } - LightPipeline lightPipeline = ao ? this.smoothLightPipeline : this.flatLightPipeline; + BlockColor blockColor = this.blockColorRegistry.getBlockColor(this.blockState.getBlock()); + int color = blockColor != null ? blockColor.getColor(this.blockState, this.renderRegion, this.blockPos, colorIndex) : -1; + color = 0xFF000000 | color; - colorizeQuad(quad, colorIndex); - shadeQuad(quad, lightPipeline, emissive, vanillaShade); - bufferQuad(terrainBuilder, this.pos, quad, this.quadLightData); + for (int i = 0; i < 4; i++) { + quad.color(i, ColorHelper.multiplyColor(color, quad.color(i))); + } } - private TerrainBuilder getBufferBuilder(BlendMode blendMode) { - if (blendMode == BlendMode.DEFAULT) { - return this.terrainBuilder; + private void shadeQuad(MutableQuadViewImpl quad, LightPipeline pipeline, boolean emissive) { + pipeline.calculate(quad, this.blockPos, this.quadLightData, quad.cullFace(), quad.lightFace(), quad.hasShade()); + + if (emissive) { + for (int i = 0; i < 4; i++) { + quad.color(i, ColorHelper.multiplyRGB(quad.color(i), this.quadLightData.br[i])); + this.quadLightData.lm[i] = net.minecraft.client.renderer.LightTexture.FULL_BRIGHT; + } } else { - TerrainRenderType renderType = TerrainRenderType.get(blendMode.blockRenderLayer); - renderType = TerrainRenderType.getRemapped(renderType); - TerrainBuilder bufferBuilder = this.resources.builderPack.builder(renderType); - bufferBuilder.setBlockAttributes(this.blockState); + for (int i = 0; i < 4; i++) { + quad.color(i, ColorHelper.multiplyRGB(quad.color(i), this.quadLightData.br[i])); + this.quadLightData.lm[i] = ColorHelper.maxBrightness(quad.lightmap(i), this.quadLightData.lm[i]); + } + } + } - return bufferBuilder; + private void copyLightData(MutableQuadViewImpl quad) { + for (int i = 0; i < 4; i++) { + quad.lightmap(i, this.quadLightData.lm[i]); } } - public void bufferQuad(TerrainBuilder terrainBuilder, Vector3f pos, ModelQuadView quad, QuadLightData quadLightData) { + private void bufferQuad(TerrainBuilder terrainBuilder, Vector3f pos, ModelQuadView quad, QuadLightData quadLightData) { QuadFacing quadFacing = quad.getQuadFacing(); - if (renderType == TerrainRenderType.TRANSLUCENT || !this.backFaceCulling) { + if (this.renderType == TerrainRenderType.TRANSLUCENT || !this.backFaceCulling) { quadFacing = QuadFacing.UNDEFINED; } TerrainBufferBuilder bufferBuilder = terrainBuilder.getBufferBuilder(quadFacing.ordinal()); - Vec3i normal = quad.getFacingDirection().getNormal(); - int packedNormal = I32_SNorm.packNormal(normal.getX(), normal.getY(), normal.getZ()); + Direction facingDirection = quad.getFacingDirection(); + int packedNormal = facingDirection != null + ? I32_SNorm.packNormal(facingDirection.getStepX(), facingDirection.getStepY(), facingDirection.getStepZ()) + : quad.getNormal(); float[] brightnessArr = quadLightData.br; int[] lights = quadLightData.lm; - // Rotate triangles if needed to fix AO anisotropy int idx = QuadUtils.getIterationStartIdx(brightnessArr, lights); bufferBuilder.ensureCapacity(); @@ -129,7 +238,6 @@ public void bufferQuad(TerrainBuilder terrainBuilder, Vector3f pos, ModelQuadVie final float z = pos.z() + quad.getZ(idx); final int quadColor = quad.getColor(idx); - int color = ColorUtil.ARGB.toRGBA(quadColor); final int light = lights[idx]; @@ -140,8 +248,112 @@ public void bufferQuad(TerrainBuilder terrainBuilder, Vector3f pos, ModelQuadVie idx = (idx + 1) & 0b11; } + } + + private boolean shouldRenderFace(@Nullable Direction face) { + if (face == null || !this.enableCulling) { + return true; + } + + int mask = 1 << face.get3DDataValue(); + if ((this.cullCompletionFlags & mask) == 0) { + this.cullCompletionFlags |= mask; + + if (faceNotOccluded(this.blockState, face)) { + this.cullResultFlags |= mask; + return true; + } + + return false; + } + return (this.cullResultFlags & mask) != 0; } -} + private boolean faceNotOccluded(BlockState state, Direction face) { + BlockGetter getter = this.renderRegion; + BlockPos adjPos = this.tempPos.setWithOffset(this.blockPos, face); + BlockState adjacent = getter.getBlockState(adjPos); + + if (state.skipRendering(adjacent, face)) { + return false; + } + if (adjacent.canOcclude()) { + var shape = state.getFaceOcclusionShape(face); + if (shape.isEmpty()) { + return true; + } + + var adjShape = adjacent.getFaceOcclusionShape(face.getOpposite()); + if (adjShape.isEmpty()) { + return true; + } + + if (shape == net.minecraft.world.phys.shapes.Shapes.block() && adjShape == net.minecraft.world.phys.shapes.Shapes.block()) { + return false; + } + + OcclusionKey key = this.lookupKey.set(state, adjacent, face); + byte cached = this.occlusionCache.getAndMoveToFirst(key); + if (cached != 127) { + return cached != 0; + } + + boolean result = net.minecraft.world.phys.shapes.Shapes.joinIsNotEmpty(shape, adjShape, net.minecraft.world.phys.shapes.BooleanOp.ONLY_FIRST); + if (this.occlusionCache.size() == 2048) { + this.occlusionCache.removeLastByte(); + } + + this.occlusionCache.putAndMoveToFirst(new OcclusionKey(state, adjacent, face), (byte) (result ? 1 : 0)); + return result; + } + + return true; + } + + public void clearCache() { + this.occlusionCache.clear(); + } + + private static final class OcclusionKey { + private BlockState state; + private BlockState adjacent; + private Direction face; + + OcclusionKey() { + } + + OcclusionKey(BlockState state, BlockState adjacent, Direction face) { + this.state = state; + this.adjacent = adjacent; + this.face = face; + } + + OcclusionKey set(BlockState state, BlockState adjacent, Direction face) { + this.state = state; + this.adjacent = adjacent; + this.face = face; + return this; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof OcclusionKey other)) { + return false; + } + return this.state == other.state && this.adjacent == other.adjacent && this.face == other.face; + } + + @Override + public int hashCode() { + int result = System.identityHashCode(this.state); + result = 31 * result + System.identityHashCode(this.adjacent); + result = 31 * result + this.face.ordinal(); + return result; + } + } +} diff --git a/src/main/java/net/vulkanmod/render/chunk/build/renderer/DefaultFluidRenderers.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/DefaultFluidRenderers.java index 0fbbe5415..6f7cf270d 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/renderer/DefaultFluidRenderers.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/DefaultFluidRenderers.java @@ -5,13 +5,13 @@ public abstract class DefaultFluidRenderers { - private static final ReferenceOpenHashSet set = new ReferenceOpenHashSet<>(); + private static final ReferenceOpenHashSet set = new ReferenceOpenHashSet<>(); - public static void add(FluidRenderHandler handler) { - set.add(handler); - } + public static void add(FluidRenderHandler handler) { + set.add(handler); + } - public static boolean has(FluidRenderHandler handler) { - return set.contains(handler); - } + public static boolean has(FluidRenderHandler handler) { + return set.contains(handler); + } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java b/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java index 30c5317f8..45617eda3 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/renderer/FluidRenderer.java @@ -40,19 +40,29 @@ public class FluidRenderer implements FluidRendering.DefaultRenderer { private final BlockPos.MutableBlockPos mBlockPos = new BlockPos.MutableBlockPos(); private final ModelQuad modelQuad = new ModelQuad(); - - BuilderResources resources; - private final LightPipeline smoothLightPipeline; private final LightPipeline flatLightPipeline; - private final int[] quadColors = new int[4]; + BuilderResources resources; public FluidRenderer(LightPipeline flatLightPipeline, LightPipeline smoothLightPipeline) { this.smoothLightPipeline = smoothLightPipeline; this.flatLightPipeline = flatLightPipeline; } + public static boolean shouldRenderFace(BlockAndTintGetter blockAndTintGetter, BlockPos blockPos, FluidState fluidState, BlockState blockState, Direction direction, BlockState adjBlockState) { + + if (adjBlockState.getFluidState().getType().isSame(fluidState.getType())) + return false; + + // self-occlusion by waterlogging + if (blockState.canOcclude()) { + return !blockState.isFaceSturdy(blockAndTintGetter, blockPos, direction); + } + + return true; + } + public void setResources(BuilderResources resources) { this.resources = resources; } @@ -60,7 +70,7 @@ public void setResources(BuilderResources resources) { public void renderLiquid(BlockState blockState, FluidState fluidState, BlockPos blockPos) { FluidRenderHandler handler = FluidRenderHandlerRegistry.INSTANCE.get(fluidState.getType()); - TerrainRenderType renderType = TerrainRenderType.get(ItemBlockRenderTypes.getRenderLayer(fluidState)); + TerrainRenderType renderType = TerrainRenderType.fromChunkLayer(ItemBlockRenderTypes.getRenderLayer(fluidState)); renderType = TerrainRenderType.getRemapped(renderType); TerrainBufferBuilder bufferBuilder = this.resources.builderPack.builder(renderType).getBufferBuilder(QuadFacing.UNDEFINED.ordinal()); @@ -70,14 +80,14 @@ public void renderLiquid(BlockState blockState, FluidState fluidState, BlockPos handler = FluidRenderHandlerRegistry.INSTANCE.get(isLava ? Fluids.LAVA : Fluids.WATER); } - FluidRendering.render(handler, this.resources.getRegion(),blockPos, bufferBuilder, blockState, fluidState, this); + FluidRendering.render(handler, this.resources.getRegion(), blockPos, bufferBuilder, blockState, fluidState, this); } private boolean isFaceOccludedByState(BlockGetter blockGetter, float h, Direction direction, BlockPos blockPos, BlockState blockState) { - mBlockPos.set(blockPos).offset(Direction.DOWN.getNormal()); + mBlockPos.set(blockPos).move(Direction.DOWN); if (blockState.canOcclude()) { - VoxelShape occlusionShape = blockState.getOcclusionShape(blockGetter, mBlockPos); + VoxelShape occlusionShape = blockState.getOcclusionShape(); if (occlusionShape == Shapes.block()) { return direction != Direction.UP; @@ -86,25 +96,12 @@ private boolean isFaceOccludedByState(BlockGetter blockGetter, float h, Directio } VoxelShape voxelShape = Shapes.box(0.0, 0.0, 0.0, 1.0, h, 1.0); - return Shapes.blockOccudes(voxelShape, occlusionShape, direction); + return Shapes.blockOccludes(voxelShape, occlusionShape, direction); } else { return false; } } - public static boolean shouldRenderFace(BlockAndTintGetter blockAndTintGetter, BlockPos blockPos, FluidState fluidState, BlockState blockState, Direction direction, BlockState adjBlockState) { - - if (adjBlockState.getFluidState().getType().isSame(fluidState.getType())) - return false; - - // self-occlusion by waterlogging - if (blockState.canOcclude()) { - return !blockState.isFaceSturdy(blockAndTintGetter, blockPos, direction); - } - - return true; - } - public BlockState getAdjBlockState(BlockAndTintGetter blockAndTintGetter, int x, int y, int z, Direction dir) { mBlockPos.set(x + dir.getStepX(), y + dir.getStepY(), z + dir.getStepZ()); return blockAndTintGetter.getBlockState(mBlockPos); @@ -164,14 +161,14 @@ public void render(FluidRenderHandler handler, BlockState blockState, FluidState seHeight = 1.0F; swHeight = 1.0F; } else { - float s = this.getHeight(region, fluid, mBlockPos.set(blockPos).offset(Direction.NORTH.getNormal()), northState); - float t = this.getHeight(region, fluid, mBlockPos.set(blockPos).offset(Direction.SOUTH.getNormal()), southState); - float u = this.getHeight(region, fluid, mBlockPos.set(blockPos).offset(Direction.EAST.getNormal()), eastState); - float v = this.getHeight(region, fluid, mBlockPos.set(blockPos).offset(Direction.WEST.getNormal()), westState); - neHeight = this.calculateAverageHeight(region, fluid, height, s, u, mBlockPos.set(blockPos).offset(Direction.NORTH.getNormal()).offset(Direction.EAST.getNormal())); - nwHeight = this.calculateAverageHeight(region, fluid, height, s, v, mBlockPos.set(blockPos).offset(Direction.NORTH.getNormal()).offset(Direction.WEST.getNormal())); - seHeight = this.calculateAverageHeight(region, fluid, height, t, u, mBlockPos.set(blockPos).offset(Direction.SOUTH.getNormal()).offset(Direction.EAST.getNormal())); - swHeight = this.calculateAverageHeight(region, fluid, height, t, v, mBlockPos.set(blockPos).offset(Direction.SOUTH.getNormal()).offset(Direction.WEST.getNormal())); + float s = this.getHeight(region, fluid, mBlockPos.set(blockPos).move(Direction.NORTH), northState); + float t = this.getHeight(region, fluid, mBlockPos.set(blockPos).move(Direction.SOUTH), southState); + float u = this.getHeight(region, fluid, mBlockPos.set(blockPos).move(Direction.EAST), eastState); + float v = this.getHeight(region, fluid, mBlockPos.set(blockPos).move(Direction.WEST), westState); + neHeight = this.calculateAverageHeight(region, fluid, height, s, u, mBlockPos.set(blockPos).move(Direction.NORTH).move(Direction.EAST)); + nwHeight = this.calculateAverageHeight(region, fluid, height, s, v, mBlockPos.set(blockPos).move(Direction.NORTH).move(Direction.WEST)); + seHeight = this.calculateAverageHeight(region, fluid, height, t, u, mBlockPos.set(blockPos).move(Direction.SOUTH).move(Direction.EAST)); + swHeight = this.calculateAverageHeight(region, fluid, height, t, v, mBlockPos.set(blockPos).move(Direction.SOUTH).move(Direction.WEST)); } float x0 = (posX & 15); @@ -422,7 +419,7 @@ private float getHeight(BlockAndTintGetter blockAndTintGetter, Fluid fluid, Bloc private float getHeight(BlockAndTintGetter blockAndTintGetter, Fluid fluid, BlockPos blockPos, BlockState adjBlockState) { FluidState adjFluidState = adjBlockState.getFluidState(); if (fluid.isSame(adjFluidState.getType())) { - BlockState blockState2 = blockAndTintGetter.getBlockState(blockPos.offset(Direction.UP.getNormal())); + BlockState blockState2 = blockAndTintGetter.getBlockState(blockPos.relative(Direction.UP)); return fluid.isSame(blockState2.getFluidState().getType()) ? 1.0F : adjFluidState.getOwnHeight(); } else { return !adjBlockState.isSolid() ? 0.0F : -1.0f; diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java b/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java index 068700b6d..2aaf0e668 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/BuildTask.java @@ -1,6 +1,7 @@ package net.vulkanmod.render.chunk.build.task; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; import net.minecraft.client.renderer.chunk.VisGraph; import net.minecraft.core.BlockPos; @@ -12,10 +13,10 @@ import net.vulkanmod.Initializer; import net.vulkanmod.render.chunk.RenderSection; import net.vulkanmod.render.chunk.WorldRenderer; -import net.vulkanmod.render.chunk.build.renderer.BlockRenderer; -import net.vulkanmod.render.chunk.build.renderer.FluidRenderer; import net.vulkanmod.render.chunk.build.RenderRegion; import net.vulkanmod.render.chunk.build.UploadBuffer; +import net.vulkanmod.render.chunk.build.renderer.BlockRenderer; +import net.vulkanmod.render.chunk.build.renderer.FluidRenderer; import net.vulkanmod.render.chunk.build.thread.BuilderResources; import net.vulkanmod.render.chunk.build.thread.ThreadBuilderPack; import net.vulkanmod.render.chunk.cull.QuadFacing; @@ -104,7 +105,7 @@ private CompileResult compile(float camX, float camY, float camZ, BuilderResourc blockPos.set(section.xOffset() + x, section.yOffset() + y, section.zOffset() + z); BlockState blockState = this.region.getBlockState(blockPos); - if (blockState.isSolidRender(this.region, blockPos)) { + if (blockState.isSolidRender()) { visGraph.setOpaque(blockPos); } @@ -181,13 +182,13 @@ private TerrainRenderType compactRenderTypes(TerrainRenderType renderType) { } private void handleBlockEntity(CompileResult compileResult, E blockEntity) { - BlockEntityRenderer blockEntityRenderer = Minecraft.getInstance().getBlockEntityRenderDispatcher().getRenderer(blockEntity); - if (blockEntityRenderer != null) { + BlockEntityRenderDispatcher dispatcher = Minecraft.getInstance().getBlockEntityRenderDispatcher(); + BlockEntityRenderer renderer = dispatcher.getRenderer(blockEntity); + if (renderer != null) { compileResult.blockEntities.add(blockEntity); - if (blockEntityRenderer.shouldRenderOffScreen(blockEntity)) { + if (renderer.shouldRenderOffScreen()) { compileResult.globalBlockEntities.add(blockEntity); } } - } } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/ChunkTask.java b/src/main/java/net/vulkanmod/render/chunk/build/task/ChunkTask.java index c1acc33df..5b692119a 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/ChunkTask.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/ChunkTask.java @@ -10,17 +10,19 @@ public abstract class ChunkTask { public static final boolean BENCH = true; protected static TaskDispatcher taskDispatcher; + protected final RenderSection section; + public boolean highPriority = false; + protected AtomicBoolean cancelled = new AtomicBoolean(false); + ChunkTask(RenderSection renderSection) { + this.section = renderSection; + } public static BuildTask createBuildTask(RenderSection renderSection, RenderRegion renderRegion, boolean highPriority) { return new BuildTask(renderSection, renderRegion, highPriority); } - protected AtomicBoolean cancelled = new AtomicBoolean(false); - protected final RenderSection section; - public boolean highPriority = false; - - ChunkTask(RenderSection renderSection) { - this.section = renderSection; + public static void setTaskDispatcher(TaskDispatcher dispatcher) { + taskDispatcher = dispatcher; } public abstract String name(); @@ -31,10 +33,6 @@ public void cancel() { this.cancelled.set(true); } - public static void setTaskDispatcher(TaskDispatcher dispatcher) { - taskDispatcher = dispatcher; - } - public enum Result { CANCELLED, SUCCESSFUL diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/CompileResult.java b/src/main/java/net/vulkanmod/render/chunk/build/task/CompileResult.java index 7a00bcf36..13c1d4322 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/CompileResult.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/CompileResult.java @@ -15,11 +15,9 @@ public class CompileResult { public final RenderSection renderSection; public final boolean fullUpdate; - + public final EnumMap renderedLayers = new EnumMap<>(TerrainRenderType.class); final List globalBlockEntities = new ArrayList<>(); final List blockEntities = new ArrayList<>(); - public final EnumMap renderedLayers = new EnumMap<>(TerrainRenderType.class); - VisibilitySet visibilitySet; QuadSorter.SortState transparencyState; CompiledSection compiledSection; @@ -32,7 +30,7 @@ public class CompileResult { public void updateSection() { this.renderSection.updateGlobalBlockEntities(globalBlockEntities); this.renderSection.setCompiledSection(compiledSection); - this.renderSection.setVisibility(((VisibilitySetExtended)visibilitySet).getVisibility()); + this.renderSection.setVisibility(((VisibilitySetExtended) visibilitySet).getVisibility()); this.renderSection.setCompletelyEmpty(compiledSection.isCompletelyEmpty); this.renderSection.setContainsBlockEntities(!blockEntities.isEmpty()); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/CompiledSection.java b/src/main/java/net/vulkanmod/render/chunk/build/task/CompiledSection.java index e233ab0a2..d54a3e9d7 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/CompiledSection.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/CompiledSection.java @@ -3,15 +3,14 @@ import com.google.common.collect.Lists; import net.minecraft.world.level.block.entity.BlockEntity; import net.vulkanmod.render.vertex.QuadSorter; - import org.jetbrains.annotations.Nullable; + import java.util.List; public class CompiledSection { public static final CompiledSection UNCOMPILED = new CompiledSection(); - - boolean isCompletelyEmpty = false; final List blockEntities = Lists.newArrayList(); + boolean isCompletelyEmpty = false; @Nullable QuadSorter.SortState transparencyState; public boolean hasTransparencyState() { diff --git a/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java b/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java index e9bdac845..cce281f88 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/task/TaskDispatcher.java @@ -7,24 +7,22 @@ import net.vulkanmod.render.chunk.WorldRenderer; import net.vulkanmod.render.chunk.buffer.DrawBuffers; import net.vulkanmod.render.chunk.build.UploadBuffer; -import net.vulkanmod.render.chunk.build.thread.ThreadBuilderPack; import net.vulkanmod.render.chunk.build.thread.BuilderResources; +import net.vulkanmod.render.chunk.build.thread.ThreadBuilderPack; import net.vulkanmod.render.vertex.TerrainRenderType; - import org.jetbrains.annotations.Nullable; import java.util.Queue; public class TaskDispatcher { - private final Queue compileResults = Queues.newLinkedBlockingDeque(); public final ThreadBuilderPack fixedBuffers; - + private final Queue compileResults = Queues.newLinkedBlockingDeque(); + private final Queue highPriorityTasks = Queues.newConcurrentLinkedQueue(); + private final Queue lowPriorityTasks = Queues.newConcurrentLinkedQueue(); private volatile boolean stopThreads; private Thread[] threads; private BuilderResources[] resources; private int idleThreads; - private final Queue highPriorityTasks = Queues.newConcurrentLinkedQueue(); - private final Queue lowPriorityTasks = Queues.newConcurrentLinkedQueue(); public TaskDispatcher() { this.fixedBuffers = new ThreadBuilderPack(); @@ -38,13 +36,13 @@ public void createThreads() { } public void createThreads(int n) { - if(!this.stopThreads) { + if (!this.stopThreads) { this.stopThreads(); } this.stopThreads = false; - if(this.resources != null) { + if (this.resources != null) { for (BuilderResources resources : this.resources) { resources.clear(); } @@ -71,10 +69,10 @@ public void createThreads(int n) { } private void runTaskThread(BuilderResources builderResources) { - while(!this.stopThreads) { + while (!this.stopThreads) { ChunkTask task = this.pollTask(); - if(task == null) + if (task == null) synchronized (this) { try { this.idleThreads++; @@ -85,7 +83,7 @@ private void runTaskThread(BuilderResources builderResources) { this.idleThreads--; } - if(task == null) + if (task == null) continue; task.runTask(builderResources); @@ -93,7 +91,7 @@ private void runTaskThread(BuilderResources builderResources) { } public void schedule(ChunkTask chunkTask) { - if(chunkTask == null) + if (chunkTask == null) return; if (chunkTask.highPriority) { @@ -111,14 +109,14 @@ public void schedule(ChunkTask chunkTask) { private ChunkTask pollTask() { ChunkTask task = this.highPriorityTasks.poll(); - if(task == null) + if (task == null) task = this.lowPriorityTasks.poll(); return task; } public void stopThreads() { - if(this.stopThreads) + if (this.stopThreads) return; this.stopThreads = true; @@ -140,7 +138,7 @@ public void stopThreads() { public boolean updateSections() { CompileResult result; boolean flag = false; - while((result = this.compileResults.poll()) != null) { + while ((result = this.compileResults.poll()) != null) { flag = true; doSectionUpdate(result); } @@ -162,12 +160,12 @@ private void doSectionUpdate(CompileResult compileResult) { if (chunkAreaManager.getChunkArea(renderArea.index) != renderArea) return; - if(compileResult.fullUpdate) { + if (compileResult.fullUpdate) { var renderLayers = compileResult.renderedLayers; - for(TerrainRenderType renderType : TerrainRenderType.VALUES) { + for (TerrainRenderType renderType : TerrainRenderType.VALUES) { UploadBuffer uploadBuffer = renderLayers.get(renderType); - if(uploadBuffer != null) { + if (uploadBuffer != null) { drawBuffers.upload(section, uploadBuffer, renderType); } else { section.resetDrawParameters(renderType); @@ -175,24 +173,25 @@ private void doSectionUpdate(CompileResult compileResult) { } compileResult.updateSection(); - } - else { + } else { UploadBuffer uploadBuffer = compileResult.renderedLayers.get(TerrainRenderType.TRANSLUCENT); drawBuffers.upload(section, uploadBuffer, TerrainRenderType.TRANSLUCENT); } } - public boolean isIdle() { return this.idleThreads == this.threads.length && this.compileResults.isEmpty(); } + public boolean isIdle() { + return this.idleThreads == this.threads.length && this.compileResults.isEmpty(); + } public void clearBatchQueue() { - while(!this.highPriorityTasks.isEmpty()) { + while (!this.highPriorityTasks.isEmpty()) { ChunkTask chunkTask = this.highPriorityTasks.poll(); if (chunkTask != null) { chunkTask.cancel(); } } - while(!this.lowPriorityTasks.isEmpty()) { + while (!this.lowPriorityTasks.isEmpty()) { ChunkTask chunkTask = this.lowPriorityTasks.poll(); if (chunkTask != null) { chunkTask.cancel(); diff --git a/src/main/java/net/vulkanmod/render/chunk/build/thread/BuilderResources.java b/src/main/java/net/vulkanmod/render/chunk/build/thread/BuilderResources.java index fd6e69f11..35b065ae4 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/thread/BuilderResources.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/thread/BuilderResources.java @@ -2,8 +2,6 @@ import net.vulkanmod.Initializer; import net.vulkanmod.render.chunk.RenderSection; -import net.vulkanmod.render.chunk.build.renderer.BlockRenderer; -import net.vulkanmod.render.chunk.build.renderer.FluidRenderer; import net.vulkanmod.render.chunk.build.RenderRegion; import net.vulkanmod.render.chunk.build.color.TintCache; import net.vulkanmod.render.chunk.build.light.LightMode; @@ -13,6 +11,8 @@ import net.vulkanmod.render.chunk.build.light.flat.FlatLightPipeline; import net.vulkanmod.render.chunk.build.light.smooth.NewSmoothLightPipeline; import net.vulkanmod.render.chunk.build.light.smooth.SmoothLightPipeline; +import net.vulkanmod.render.chunk.build.renderer.BlockRenderer; +import net.vulkanmod.render.chunk.build.renderer.FluidRenderer; public class BuilderResources { public final ThreadBuilderPack builderPack = new ThreadBuilderPack(); @@ -34,8 +34,7 @@ public BuilderResources() { LightPipeline smoothLightPipeline; if (Initializer.CONFIG.ambientOcclusion == LightMode.SUB_BLOCK) { smoothLightPipeline = new NewSmoothLightPipeline(lightDataCache); - } - else { + } else { smoothLightPipeline = new SmoothLightPipeline(lightDataCache); } diff --git a/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java b/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java index 84102838f..151f57d43 100644 --- a/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java +++ b/src/main/java/net/vulkanmod/render/chunk/build/thread/ThreadBuilderPack.java @@ -10,15 +10,6 @@ public class ThreadBuilderPack { private static Function terrainBuilderConstructor; - - public static void defaultTerrainBuilderConstructor() { - terrainBuilderConstructor = renderType -> new TerrainBuilder(TerrainRenderType.getRenderType(renderType).bufferSize()); - } - - public static void setTerrainBuilderConstructor(Function constructor) { - terrainBuilderConstructor = constructor; - } - private final Map builders; public ThreadBuilderPack() { @@ -30,6 +21,14 @@ public ThreadBuilderPack() { builders = map; } + public static void defaultTerrainBuilderConstructor() { + terrainBuilderConstructor = renderType -> new TerrainBuilder(TerrainRenderType.getRenderType(renderType).bufferSize()); + } + + public static void setTerrainBuilderConstructor(Function constructor) { + terrainBuilderConstructor = constructor; + } + public TerrainBuilder builder(TerrainRenderType renderType) { return this.builders.get(renderType); } @@ -38,4 +37,4 @@ public void clearAll() { this.builders.values().forEach(TerrainBuilder::clear); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java b/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java index 642fd9bf4..a51bf47f2 100644 --- a/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java +++ b/src/main/java/net/vulkanmod/render/chunk/cull/QuadFacing.java @@ -63,4 +63,4 @@ public static QuadFacing fromNormal(float x, float y, float z) { return QuadFacing.UNDEFINED; } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/frustum/VFrustum.java b/src/main/java/net/vulkanmod/render/chunk/frustum/VFrustum.java index 396e1f4dd..158ca23ef 100644 --- a/src/main/java/net/vulkanmod/render/chunk/frustum/VFrustum.java +++ b/src/main/java/net/vulkanmod/render/chunk/frustum/VFrustum.java @@ -6,14 +6,13 @@ import org.joml.Vector4f; public class VFrustum { + private final FrustumIntersection frustum = new FrustumIntersection(); + private final Matrix4f matrix = new Matrix4f(); private Vector4f viewVector = new Vector4f(); private double camX; private double camY; private double camZ; - private final FrustumIntersection frustum = new FrustumIntersection(); - private final Matrix4f matrix = new Matrix4f(); - public VFrustum offsetToFullyIncludeCameraCube(int offset) { double d0 = Math.floor(this.camX / (double) offset) * (double) offset; double d1 = Math.floor(this.camY / (double) offset) * (double) offset; diff --git a/src/main/java/net/vulkanmod/render/chunk/graph/GraphDirections.java b/src/main/java/net/vulkanmod/render/chunk/graph/GraphDirections.java index e570ba2b2..36529b607 100644 --- a/src/main/java/net/vulkanmod/render/chunk/graph/GraphDirections.java +++ b/src/main/java/net/vulkanmod/render/chunk/graph/GraphDirections.java @@ -7,4 +7,4 @@ public abstract class GraphDirections { public static final int SOUTH = 3; public static final int WEST = 4; public static final int EAST = 5; -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/graph/SectionGraph.java b/src/main/java/net/vulkanmod/render/chunk/graph/SectionGraph.java index 8a3d641be..2396f671d 100644 --- a/src/main/java/net/vulkanmod/render/chunk/graph/SectionGraph.java +++ b/src/main/java/net/vulkanmod/render/chunk/graph/SectionGraph.java @@ -11,7 +11,10 @@ import net.minecraft.world.phys.Vec3; import net.vulkanmod.Initializer; import net.vulkanmod.interfaces.FrustumMixed; -import net.vulkanmod.render.chunk.*; +import net.vulkanmod.render.chunk.ChunkAreaManager; +import net.vulkanmod.render.chunk.RenderSection; +import net.vulkanmod.render.chunk.SectionGrid; +import net.vulkanmod.render.chunk.WorldRenderer; import net.vulkanmod.render.chunk.build.RenderRegionBuilder; import net.vulkanmod.render.chunk.build.task.TaskDispatcher; import net.vulkanmod.render.chunk.frustum.VFrustum; @@ -23,23 +26,19 @@ import java.util.List; public class SectionGraph { - Minecraft minecraft; private final Level level; - private final SectionGrid sectionGrid; private final ChunkAreaManager chunkAreaManager; private final TaskDispatcher taskDispatcher; private final ResettableQueue sectionQueue = new ResettableQueue<>(); - private AreaSetQueue chunkAreaQueue; - private short lastFrame = 0; - private final ResettableQueue blockEntitiesSections = new ResettableQueue<>(); private final ResettableQueue rebuildQueue = new ResettableQueue<>(); - - private VFrustum frustum; - public RenderRegionBuilder renderRegionCache; + Minecraft minecraft; int nonEmptyChunks; + private AreaSetQueue chunkAreaQueue; + private short lastFrame = 0; + private VFrustum frustum; public SectionGraph(Level level, SectionGrid sectionGrid, TaskDispatcher taskDispatcher) { @@ -53,15 +52,35 @@ public SectionGraph(Level level, SectionGrid sectionGrid, TaskDispatcher taskDis this.renderRegionCache = WorldRenderer.getInstance().renderRegionCache; } + private static void initFirstNode(RenderSection renderSection, short frame) { + renderSection.mainDir = 7; + renderSection.sourceDirs = (byte) (1 << 7); + renderSection.directions = (byte) 0xFF; + renderSection.setLastFrame(frame); + renderSection.visibility |= initVisibility(); + renderSection.directionChanges = 0; + renderSection.steps = 0; + } + + // Init special value used by first graph node + private static long initVisibility() { + long vis = 0; + for (int dir = 0; dir < 6; dir++) { + vis |= 1L << ((6 << 3) + dir); + vis |= 1L << ((7 << 3) + dir); + } + + return vis; + } + public void update(Camera camera, Frustum frustum, boolean spectator) { Profiler profiler = Profiler.getMainProfiler(); + profiler.push("update"); BlockPos blockpos = camera.getBlockPosition(); - this.minecraft.getProfiler().popPush("update"); - boolean flag = this.minecraft.smartCull; - if (spectator && this.level.getBlockState(blockpos).isSolidRender(this.level, blockpos)) { + if (spectator && this.level.getBlockState(blockpos).isSolidRender()) { flag = false; } @@ -70,7 +89,7 @@ public void update(Camera camera, Frustum frustum, boolean spectator) { this.sectionGrid.updateFrustumVisibility(this.frustum); profiler.pop(); - this.minecraft.getProfiler().push("partial_update"); + profiler.push("partial_update"); this.initUpdate(); this.initializeQueueForFullUpdate(camera); @@ -82,7 +101,8 @@ public void update(Camera camera, Frustum frustum, boolean spectator) { this.scheduleRebuilds(); - this.minecraft.getProfiler().pop(); + profiler.pop(); // partial_update + profiler.pop(); // update } private void initializeQueueForFullUpdate(Camera camera) { @@ -91,8 +111,8 @@ private void initializeQueueForFullUpdate(Camera camera) { RenderSection renderSection = this.sectionGrid.getSectionAtBlockPos(blockpos); if (renderSection == null) { - boolean flag = blockpos.getY() > this.level.getMinBuildHeight(); - int y = flag ? this.level.getMaxBuildHeight() - 8 : this.level.getMinBuildHeight() + 8; + boolean flag = blockpos.getY() > this.level.getMinY(); + int y = flag ? this.level.getMaxY() - 8 : this.level.getMinY() + 8; int x = Mth.floor(vec3.x / 16.0D) * 16; int z = Mth.floor(vec3.z / 16.0D) * 16; @@ -123,27 +143,6 @@ private void initializeQueueForFullUpdate(Camera camera) { } - private static void initFirstNode(RenderSection renderSection, short frame) { - renderSection.mainDir = 7; - renderSection.sourceDirs = (byte) (1 << 7); - renderSection.directions = (byte) 0xFF; - renderSection.setLastFrame(frame); - renderSection.visibility |= initVisibility(); - renderSection.directionChanges = 0; - renderSection.steps = 0; - } - - // Init special value used by first graph node - private static long initVisibility() { - long vis = 0; - for (int dir = 0; dir < 6; dir++) { - vis |= 1L << ((6 << 3) + dir); - vis |= 1L << ((7 << 3) + dir); - } - - return vis; - } - private void initUpdate() { this.resetUpdateQueues(); @@ -318,4 +317,3 @@ public String getStatistics() { return String.format("Chunks: %d(%d)/%d D: %d, %s", this.nonEmptyChunks, sections, totalSections, renderDistance, tasksInfo); } } - diff --git a/src/main/java/net/vulkanmod/render/chunk/util/BufferUtil.java b/src/main/java/net/vulkanmod/render/chunk/util/BufferUtil.java index fb9bcd6e2..0ecb2ef8d 100644 --- a/src/main/java/net/vulkanmod/render/chunk/util/BufferUtil.java +++ b/src/main/java/net/vulkanmod/render/chunk/util/BufferUtil.java @@ -15,4 +15,4 @@ public static ByteBuffer clone(ByteBuffer src) { public static ByteBuffer bufferSlice(ByteBuffer buffer, int start, int end) { return MemoryUtil.memSlice(buffer, start, end - start); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/chunk/util/CircularIntList.java b/src/main/java/net/vulkanmod/render/chunk/util/CircularIntList.java index d8964eaa9..9d33fa9ff 100644 --- a/src/main/java/net/vulkanmod/render/chunk/util/CircularIntList.java +++ b/src/main/java/net/vulkanmod/render/chunk/util/CircularIntList.java @@ -7,10 +7,9 @@ public class CircularIntList { private final int size; private final int[] list; - private int startIndex; - private final OwnIterator iterator; private final RangeIterator rangeIterator; + private int startIndex; public CircularIntList(int size) { this.size = size; @@ -28,11 +27,11 @@ public void updateStartIdx(int startIndex) { list[size + 1] = -1; int k = 1; - for(int i = startIndex; i < size; ++i) { + for (int i = startIndex; i < size; ++i) { list[k] = i; ++k; } - for(int i = 0; i < startIndex; ++i) { + for (int i = 0; i < startIndex; ++i) { list[k] = i; ++k; } @@ -60,8 +59,8 @@ public RangeIterator createRangeIterator() { } public class OwnIterator implements Iterator { - private int currentIndex = 0; private final int maxIndex = size; + private int currentIndex = 0; @Override public boolean hasNext() { diff --git a/src/main/java/net/vulkanmod/render/chunk/util/ResettableQueue.java b/src/main/java/net/vulkanmod/render/chunk/util/ResettableQueue.java index 910b435a4..9893bebe5 100644 --- a/src/main/java/net/vulkanmod/render/chunk/util/ResettableQueue.java +++ b/src/main/java/net/vulkanmod/render/chunk/util/ResettableQueue.java @@ -73,8 +73,8 @@ public void clear() { public Iterator iterator(boolean reverseOrder) { return reverseOrder ? new Iterator<>() { - int pos = ResettableQueue.this.limit - 1; final int limit = -1; + int pos = ResettableQueue.this.limit - 1; @Override public boolean hasNext() { @@ -87,8 +87,8 @@ public T next() { } } : new Iterator<>() { - int pos = 0; final int limit = ResettableQueue.this.limit; + int pos = 0; @Override public boolean hasNext() { diff --git a/src/main/java/net/vulkanmod/render/chunk/util/SimpleDirection.java b/src/main/java/net/vulkanmod/render/chunk/util/SimpleDirection.java index b4c53e808..75bdd757d 100644 --- a/src/main/java/net/vulkanmod/render/chunk/util/SimpleDirection.java +++ b/src/main/java/net/vulkanmod/render/chunk/util/SimpleDirection.java @@ -12,17 +12,11 @@ public enum SimpleDirection { EAST(5, 4, 3, new Vec3i(1, 0, 0)); private static final SimpleDirection[] VALUES = SimpleDirection.values(); - - public static SimpleDirection of(Direction direction) { - return VALUES[direction.get3DDataValue()]; - } - + public final byte nx, ny, nz; private final int data3d; private final int oppositeIndex; private final int data2d; - public final byte nx, ny, nz; - SimpleDirection(int j, int k, int l, Vec3i normal) { this.data3d = j; this.oppositeIndex = k; @@ -33,6 +27,10 @@ public static SimpleDirection of(Direction direction) { this.nz = (byte) normal.getZ(); } + public static SimpleDirection of(Direction direction) { + return VALUES[direction.get3DDataValue()]; + } + public int get3DDataValue() { return this.data3d; } diff --git a/src/main/java/net/vulkanmod/render/chunk/util/StaticQueue.java b/src/main/java/net/vulkanmod/render/chunk/util/StaticQueue.java index 2d811c072..b2a919a4e 100644 --- a/src/main/java/net/vulkanmod/render/chunk/util/StaticQueue.java +++ b/src/main/java/net/vulkanmod/render/chunk/util/StaticQueue.java @@ -7,9 +7,9 @@ public class StaticQueue implements Iterable { final T[] queue; + final int capacity; int position = 0; int limit = 0; - final int capacity; public StaticQueue() { this(1024); @@ -48,8 +48,8 @@ public void clear() { public Iterator iterator(boolean reverseOrder) { return reverseOrder ? new Iterator<>() { - int pos = StaticQueue.this.limit - 1; final int limit = -1; + int pos = StaticQueue.this.limit - 1; @Override public boolean hasNext() { @@ -62,8 +62,8 @@ public T next() { } } : new Iterator<>() { - int pos = 0; final int limit = StaticQueue.this.limit; + int pos = 0; @Override public boolean hasNext() { diff --git a/src/main/java/net/vulkanmod/render/chunk/util/Util.java b/src/main/java/net/vulkanmod/render/chunk/util/Util.java index caa063410..81be1eae0 100644 --- a/src/main/java/net/vulkanmod/render/chunk/util/Util.java +++ b/src/main/java/net/vulkanmod/render/chunk/util/Util.java @@ -1,9 +1,6 @@ package net.vulkanmod.render.chunk.util; import net.minecraft.core.Direction; -import org.lwjgl.system.MemoryUtil; - -import java.nio.ByteBuffer; public class Util { diff --git a/src/main/java/net/vulkanmod/render/material/BlendMode.java b/src/main/java/net/vulkanmod/render/material/BlendMode.java new file mode 100644 index 000000000..3c00b6eff --- /dev/null +++ b/src/main/java/net/vulkanmod/render/material/BlendMode.java @@ -0,0 +1,23 @@ +package net.vulkanmod.render.material; + +/** + * Blend mode indicator used by VulkanMod's material system. + *

+ * The enum is intentionally small – only the modes referenced by + * the existing chunk and item renderers are implemented. Additional + * modes can be added later without breaking the binary layout used + * by encoded quads. + */ +public enum BlendMode { + DEFAULT, + CUTOUT, + CUTOUT_MIPPED, + TRANSLUCENT; + + /** + * Returns {@code true} when this mode should render with translucency. + */ + public boolean isTranslucent() { + return this == TRANSLUCENT; + } +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/material/RenderMaterial.java b/src/main/java/net/vulkanmod/render/material/RenderMaterial.java new file mode 100644 index 000000000..6a5da91e5 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/material/RenderMaterial.java @@ -0,0 +1,110 @@ +package net.vulkanmod.render.material; + +import net.vulkanmod.util.TriState; + +import java.util.Objects; + +/** + * Immutable material descriptor used by the new rendering path. + *

+ * Materials are interned via {@link RenderMaterialRegistry} so instances + * can be compared with {@code ==} once retrieved from the registry. + */ +public final class RenderMaterial { + private final BlendMode blendMode; + private final boolean disableColorIndex; + private final boolean emissive; + private final boolean disableDiffuse; + private final TriState ambientOcclusion; + private final TriState glint; + private final ShadeMode shadeMode; + + RenderMaterial(BlendMode blendMode, + boolean disableColorIndex, + boolean emissive, + boolean disableDiffuse, + TriState ambientOcclusion, + TriState glint, + ShadeMode shadeMode) { + this.blendMode = Objects.requireNonNull(blendMode, "blendMode"); + this.ambientOcclusion = Objects.requireNonNull(ambientOcclusion, "ambientOcclusion"); + this.glint = Objects.requireNonNull(glint, "glint"); + this.shadeMode = Objects.requireNonNull(shadeMode, "shadeMode"); + this.disableColorIndex = disableColorIndex; + this.emissive = emissive; + this.disableDiffuse = disableDiffuse; + } + + public BlendMode blendMode() { + return this.blendMode; + } + + public boolean disableColorIndex() { + return this.disableColorIndex; + } + + public boolean emissive() { + return this.emissive; + } + + public boolean disableDiffuse() { + return this.disableDiffuse; + } + + public TriState ambientOcclusion() { + return this.ambientOcclusion; + } + + public TriState glint() { + return this.glint; + } + + public ShadeMode shadeMode() { + return this.shadeMode; + } + + RenderMaterial withDisableDiffuse(boolean disable) { + if (disable == this.disableDiffuse) { + return this; + } + + return RenderMaterialRegistry.intern(new RenderMaterial(this.blendMode, + this.disableColorIndex, + this.emissive, + disable, + this.ambientOcclusion, + this.glint, + this.shadeMode)); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (!(o instanceof RenderMaterial that)) { + return false; + } + + return this.disableColorIndex == that.disableColorIndex + && this.emissive == that.emissive + && this.disableDiffuse == that.disableDiffuse + && this.blendMode == that.blendMode + && this.ambientOcclusion == that.ambientOcclusion + && this.glint == that.glint + && this.shadeMode == that.shadeMode; + } + + @Override + public int hashCode() { + int result = this.blendMode.hashCode(); + result = 31 * result + Boolean.hashCode(this.disableColorIndex); + result = 31 * result + Boolean.hashCode(this.emissive); + result = 31 * result + Boolean.hashCode(this.disableDiffuse); + result = 31 * result + this.ambientOcclusion.hashCode(); + result = 31 * result + this.glint.hashCode(); + result = 31 * result + this.shadeMode.hashCode(); + return result; + } +} diff --git a/src/main/java/net/vulkanmod/render/material/RenderMaterialBuilder.java b/src/main/java/net/vulkanmod/render/material/RenderMaterialBuilder.java new file mode 100644 index 000000000..141e17ad1 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/material/RenderMaterialBuilder.java @@ -0,0 +1,85 @@ +package net.vulkanmod.render.material; + +import net.vulkanmod.util.TriState; + +/** + * Fluent builder used to construct {@link RenderMaterial} instances. + * Works similarly to Fabric's MaterialFinder but only exposes the knobs + * relied upon by VulkanMod. + */ +public final class RenderMaterialBuilder { + private BlendMode blendMode = BlendMode.DEFAULT; + private boolean disableColorIndex; + private boolean emissive; + private boolean disableDiffuse; + private TriState ambientOcclusion = TriState.DEFAULT; + private TriState glint = TriState.DEFAULT; + private ShadeMode shadeMode = ShadeMode.VANILLA; + + public RenderMaterialBuilder blendMode(BlendMode blendMode) { + this.blendMode = blendMode; + return this; + } + + public RenderMaterialBuilder disableColorIndex(boolean disable) { + this.disableColorIndex = disable; + return this; + } + + public RenderMaterialBuilder emissive(boolean emissive) { + this.emissive = emissive; + return this; + } + + public RenderMaterialBuilder disableDiffuse(boolean disable) { + this.disableDiffuse = disable; + return this; + } + + public RenderMaterialBuilder ambientOcclusion(TriState ao) { + this.ambientOcclusion = ao; + return this; + } + + public RenderMaterialBuilder glint(TriState glintMode) { + this.glint = glintMode; + return this; + } + + public RenderMaterialBuilder shadeMode(ShadeMode shadeMode) { + this.shadeMode = shadeMode; + return this; + } + + public RenderMaterialBuilder copyFrom(RenderMaterial material) { + this.blendMode = material.blendMode(); + this.disableColorIndex = material.disableColorIndex(); + this.emissive = material.emissive(); + this.disableDiffuse = material.disableDiffuse(); + this.ambientOcclusion = material.ambientOcclusion(); + this.glint = material.glint(); + this.shadeMode = material.shadeMode(); + return this; + } + + public RenderMaterialBuilder clear() { + this.blendMode = BlendMode.DEFAULT; + this.disableColorIndex = false; + this.emissive = false; + this.disableDiffuse = false; + this.ambientOcclusion = TriState.DEFAULT; + this.glint = TriState.DEFAULT; + this.shadeMode = ShadeMode.VANILLA; + return this; + } + + public RenderMaterial build() { + return RenderMaterialRegistry.intern(new RenderMaterial(this.blendMode, + this.disableColorIndex, + this.emissive, + this.disableDiffuse, + this.ambientOcclusion, + this.glint, + this.shadeMode)); + } +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/material/RenderMaterialRegistry.java b/src/main/java/net/vulkanmod/render/material/RenderMaterialRegistry.java new file mode 100644 index 000000000..3af7058f9 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/material/RenderMaterialRegistry.java @@ -0,0 +1,77 @@ +package net.vulkanmod.render.material; + +import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.objects.Object2IntMap; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import net.vulkanmod.util.TriState; + +/** + * Central registry for {@link RenderMaterial} instances. Quads encode the + * registry index to avoid storing large structures per vertex. + */ +public final class RenderMaterialRegistry { + public static final RenderMaterial STANDARD_MATERIAL; + public static final RenderMaterial NO_AO_MATERIAL; + private static final Int2ObjectMap BY_ID = new Int2ObjectArrayMap<>(); + private static final Object2IntMap TO_ID = new Object2IntOpenHashMap<>(); + private static int nextId; + + static { + TO_ID.defaultReturnValue(-1); + + STANDARD_MATERIAL = intern(new RenderMaterial(BlendMode.DEFAULT, + false, + false, + false, + TriState.DEFAULT, + TriState.DEFAULT, + ShadeMode.VANILLA)); + + NO_AO_MATERIAL = intern(new RenderMaterial(BlendMode.DEFAULT, + false, + false, + false, + TriState.FALSE, + TriState.DEFAULT, + ShadeMode.VANILLA)); + } + + private RenderMaterialRegistry() { + } + + public static synchronized RenderMaterial intern(RenderMaterial material) { + int id = TO_ID.getInt(material); + if (id != -1) { + return BY_ID.get(id); + } + + id = nextId++; + TO_ID.put(material, id); + BY_ID.put(id, material); + return material; + } + + public static synchronized int getId(RenderMaterial material) { + int id = TO_ID.getInt(material); + if (id == -1) { + id = nextId++; + TO_ID.put(material, id); + BY_ID.put(id, material); + } + return id; + } + + public static RenderMaterial fromId(int id) { + RenderMaterial material = BY_ID.get(id); + if (material == null) { + throw new IllegalStateException("Unknown material id " + id); + } + + return material; + } + + public static RenderMaterial disableDiffuse(RenderMaterial material, boolean disable) { + return material.withDisableDiffuse(disable); + } +} diff --git a/src/main/java/net/vulkanmod/render/material/ShadeMode.java b/src/main/java/net/vulkanmod/render/material/ShadeMode.java new file mode 100644 index 000000000..f94be7612 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/material/ShadeMode.java @@ -0,0 +1,10 @@ +package net.vulkanmod.render.material; + +/** + * Describes how a quad should be shaded. Currently only provides parity with + * the vanilla Fabric API behaviour that VulkanMod relied on. + */ +public enum ShadeMode { + VANILLA, + FLAT +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/model/CubeModel.java b/src/main/java/net/vulkanmod/render/model/CubeModel.java deleted file mode 100644 index da988f39d..000000000 --- a/src/main/java/net/vulkanmod/render/model/CubeModel.java +++ /dev/null @@ -1,115 +0,0 @@ -package net.vulkanmod.render.model; - -import net.minecraft.client.model.geom.ModelPart; -import net.minecraft.core.Direction; -import org.joml.Matrix4f; -import org.joml.Vector3f; - -import java.util.Set; - -public class CubeModel { - - private ModelPart.Polygon[] polygons = new ModelPart.Polygon[6]; - public float minX; - public float minY; - public float minZ; - public float maxX; - public float maxY; - public float maxZ; - - Vector3f[] vertices; - Vector3f[] transformed = new Vector3f[8]; - - public void setVertices(int i, int j, float f, float g, float h, float k, float l, float m, float n, float o, float p, boolean bl, float q, float r, Set set) { - this.minX = f; - this.minY = g; - this.minZ = h; - this.maxX = f + k; - this.maxY = g + l; - this.maxZ = h + m; - this.polygons = new ModelPart.Polygon[set.size()]; - float s = maxX; - float t = maxY; - float u = maxZ; - f -= n; - g -= o; - h -= p; - s += n; - t += o; - u += p; - if (bl) { - float v = s; - s = f; - f = v; - } - - this.vertices = new Vector3f[]{ - new Vector3f(f, g, h), - new Vector3f(s, g, h), - new Vector3f(s, t, h), - new Vector3f(f, t, h), - new Vector3f(f, g, u), - new Vector3f(s, g, u), - new Vector3f(s, t, u), - new Vector3f(f, t, u) - }; - - for (int i1 = 0; i1 < 8; i1++) { - //pre-divide all vertices once - this.vertices[i1].div(16.0f); - this.transformed[i1] = new Vector3f(0.0f); - } - - ModelPart.Vertex vertex1 = new ModelPart.Vertex(transformed[0], 0.0F, 0.0F); - ModelPart.Vertex vertex2 = new ModelPart.Vertex(transformed[1], 0.0F, 8.0F); - ModelPart.Vertex vertex3 = new ModelPart.Vertex(transformed[2], 8.0F, 8.0F); - ModelPart.Vertex vertex4 = new ModelPart.Vertex(transformed[3], 8.0F, 0.0F); - ModelPart.Vertex vertex5 = new ModelPart.Vertex(transformed[4], 0.0F, 0.0F); - ModelPart.Vertex vertex6 = new ModelPart.Vertex(transformed[5], 0.0F, 8.0F); - ModelPart.Vertex vertex7 = new ModelPart.Vertex(transformed[6], 8.0F, 8.0F); - ModelPart.Vertex vertex8 = new ModelPart.Vertex(transformed[7], 8.0F, 0.0F); - - float w = (float)i; - float x = (float)i + m; - float y = (float)i + m + k; - float z = (float)i + m + k + k; - float aa = (float)i + m + k + m; - float ab = (float)i + m + k + m + k; - float ac = (float)j; - float ad = (float)j + m; - float ae = (float)j + m + l; - int idx = 0; - if (set.contains(Direction.DOWN)) { - this.polygons[idx++] = new ModelPart.Polygon(new ModelPart.Vertex[]{vertex6, vertex5, vertex1, vertex2}, x, ac, y, ad, q, r, bl, Direction.DOWN); - } - - if (set.contains(Direction.UP)) { - this.polygons[idx++] = new ModelPart.Polygon(new ModelPart.Vertex[]{vertex3, vertex4, vertex8, vertex7}, y, ad, z, ac, q, r, bl, Direction.UP); - } - - if (set.contains(Direction.WEST)) { - this.polygons[idx++] = new ModelPart.Polygon(new ModelPart.Vertex[]{vertex1, vertex5, vertex8, vertex4}, w, ad, x, ae, q, r, bl, Direction.WEST); - } - - if (set.contains(Direction.NORTH)) { - this.polygons[idx++] = new ModelPart.Polygon(new ModelPart.Vertex[]{vertex2, vertex1, vertex4, vertex3}, x, ad, y, ae, q, r, bl, Direction.NORTH); - } - - if (set.contains(Direction.EAST)) { - this.polygons[idx++] = new ModelPart.Polygon(new ModelPart.Vertex[]{vertex6, vertex2, vertex3, vertex7}, y, ad, aa, ae, q, r, bl, Direction.EAST); - } - - if (set.contains(Direction.SOUTH)) { - this.polygons[idx] = new ModelPart.Polygon(new ModelPart.Vertex[]{vertex5, vertex6, vertex7, vertex8}, aa, ad, ab, ae, q, r, bl, Direction.SOUTH); - } - } - - public void transformVertices(Matrix4f matrix) { - //Transform original vertices and store them - for(int i = 0; i < 8; ++i) { - this.vertices[i].mulPosition(matrix, this.transformed[i]); - } - } - - public ModelPart.Polygon[] getPolygons() { return this.polygons; } -} diff --git a/src/main/java/net/vulkanmod/render/model/ModelHelper.java b/src/main/java/net/vulkanmod/render/model/ModelHelper.java new file mode 100644 index 000000000..e2943bf92 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/model/ModelHelper.java @@ -0,0 +1,30 @@ +package net.vulkanmod.render.model; + +import net.minecraft.core.Direction; +import org.jetbrains.annotations.Nullable; + +/** + * Simple helper mirroring the handful of face-index utilities that were + * previously provided by Fabric's ModelHelper. + */ +public final class ModelHelper { + public static final int NULL_FACE_ID = Direction.values().length; + + private static final Direction[] DIRECTIONS = Direction.values(); + + private ModelHelper() { + } + + public static int toFaceIndex(@Nullable Direction face) { + return face == null ? NULL_FACE_ID : face.get3DDataValue(); + } + + @Nullable + public static Direction faceFromIndex(int index) { + if (index < 0 || index >= NULL_FACE_ID) { + return null; + } + + return DIRECTIONS[index]; + } +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/model/quad/ModelQuad.java b/src/main/java/net/vulkanmod/render/model/quad/ModelQuad.java index d87df233d..9316097c1 100644 --- a/src/main/java/net/vulkanmod/render/model/quad/ModelQuad.java +++ b/src/main/java/net/vulkanmod/render/model/quad/ModelQuad.java @@ -9,23 +9,24 @@ */ public class ModelQuad implements ModelQuadView { public static final int VERTEX_SIZE = 8; + private final int[] data = new int[4 * VERTEX_SIZE]; + Direction direction; + TextureAtlasSprite sprite; + private int flags; public static int vertexOffset(int vertexIndex) { return vertexIndex * VERTEX_SIZE; } - private final int[] data = new int[4 * VERTEX_SIZE]; - - Direction direction; - TextureAtlasSprite sprite; - - private int flags; - @Override public int getFlags() { return flags; } + public void setFlags(int f) { + this.flags = f; + } + @Override public float getX(int idx) { return Float.intBitsToFloat(this.data[vertexOffset(idx)]); @@ -104,10 +105,6 @@ public float setV(int idx, float f) { } - public void setFlags(int f) { - this.flags = f; - } - public void setSprite(TextureAtlasSprite sprite) { this.sprite = sprite; } diff --git a/src/main/java/net/vulkanmod/render/model/quad/ModelQuadFlags.java b/src/main/java/net/vulkanmod/render/model/quad/ModelQuadFlags.java index bb1dc0cca..41bd087c7 100644 --- a/src/main/java/net/vulkanmod/render/model/quad/ModelQuadFlags.java +++ b/src/main/java/net/vulkanmod/render/model/quad/ModelQuadFlags.java @@ -51,7 +51,7 @@ public static int getQuadFlags(ModelQuadView quad, Direction face) { case Z -> minX >= 0.0001f || minY >= 0.0001f || maxX <= 0.9999F || maxY <= 0.9999F; }; - boolean parallel = switch(face.getAxis()) { + boolean parallel = switch (face.getAxis()) { case X -> minX == maxX; case Y -> minY == maxY; case Z -> minZ == maxZ; diff --git a/src/main/java/net/vulkanmod/render/model/quad/ModelQuadView.java b/src/main/java/net/vulkanmod/render/model/quad/ModelQuadView.java index ac791d9a5..8eda41f25 100644 --- a/src/main/java/net/vulkanmod/render/model/quad/ModelQuadView.java +++ b/src/main/java/net/vulkanmod/render/model/quad/ModelQuadView.java @@ -34,4 +34,4 @@ default boolean isTinted() { } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/model/quad/QuadUtils.java b/src/main/java/net/vulkanmod/render/model/quad/QuadUtils.java index 9f7c7f1d7..f1500d1c4 100644 --- a/src/main/java/net/vulkanmod/render/model/quad/QuadUtils.java +++ b/src/main/java/net/vulkanmod/render/model/quad/QuadUtils.java @@ -10,9 +10,9 @@ public abstract class QuadUtils { public static int getIterationStartIdx(float[] aos, int[] lms) { final float ao00_11 = aos[0] + aos[2]; final float ao10_01 = aos[1] + aos[3]; - if(ao00_11 > ao10_01) { + if (ao00_11 > ao10_01) { return DEFAULT_START_IDX; - } else if(ao00_11 < ao10_01) { + } else if (ao00_11 < ao10_01) { return FLIPPED_START_IDX; } @@ -24,7 +24,7 @@ public static int getIterationStartIdx(float[] aos, int[] lms) { // return FLIPPED_START_IDX; // } - if(lm00_11 >= lm10_01) { + if (lm00_11 >= lm10_01) { return FLIPPED_START_IDX; } else { return DEFAULT_START_IDX; @@ -37,7 +37,7 @@ public static int getIterationStartIdx(float[] aos, int[] lms) { public static int getIterationStartIdx(float[] aos) { final float ao00_11 = aos[0] + aos[2]; final float ao10_01 = aos[1] + aos[3]; - if(ao00_11 >= ao10_01) { + if (ao00_11 >= ao10_01) { return DEFAULT_START_IDX; } else { return FLIPPED_START_IDX; diff --git a/src/main/java/net/vulkanmod/render/pipeline/VulkanPipelineCompiler.java b/src/main/java/net/vulkanmod/render/pipeline/VulkanPipelineCompiler.java new file mode 100644 index 000000000..6e6dcdcdc --- /dev/null +++ b/src/main/java/net/vulkanmod/render/pipeline/VulkanPipelineCompiler.java @@ -0,0 +1,27 @@ +package net.vulkanmod.render.pipeline; + +import com.mojang.blaze3d.pipeline.RenderPipeline; +import net.vulkanmod.vulkan.shader.GraphicsPipeline; +import net.vulkanmod.vulkan.shader.Pipeline; +import net.vulkanmod.vulkan.shader.converter.GlslConverter; +import net.vulkanmod.vulkan.shader.descriptor.UBO; + +import java.util.Collections; + +public final class VulkanPipelineCompiler { + private VulkanPipelineCompiler() { + } + + public static GraphicsPipeline compile(RenderPipeline pipeline, String vertexSource, String fragmentSource) { + GlslConverter converter = new GlslConverter(); + converter.process(vertexSource, fragmentSource); + + UBO ubo = converter.createUBO(); + + Pipeline.Builder builder = new Pipeline.Builder(pipeline.getVertexFormat(), pipeline.getLocation().toString()); + builder.setUniforms(Collections.singletonList(ubo), converter.getSamplerList()); + builder.compileShaders(pipeline.getLocation().toString(), converter.getVshConverted(), converter.getFshConverted()); + + return builder.createGraphicsPipeline(); + } +} diff --git a/src/main/java/net/vulkanmod/render/profiling/BuildTimeProfiler.java b/src/main/java/net/vulkanmod/render/profiling/BuildTimeProfiler.java index f93c28fb7..e7455a599 100644 --- a/src/main/java/net/vulkanmod/render/profiling/BuildTimeProfiler.java +++ b/src/main/java/net/vulkanmod/render/profiling/BuildTimeProfiler.java @@ -9,12 +9,12 @@ public abstract class BuildTimeProfiler { private static float deltaTime; public static void runBench(boolean building) { - if(bench) { + if (bench) { if (startTime == 0) { startTime = System.nanoTime(); } - if(!building) { + if (!building) { deltaTime = (System.nanoTime() - startTime) * 0.000001f; bench = false; startTime = 0; diff --git a/src/main/java/net/vulkanmod/render/profiling/Profiler.java b/src/main/java/net/vulkanmod/render/profiling/Profiler.java index ccfe5cb59..4287d36b5 100644 --- a/src/main/java/net/vulkanmod/render/profiling/Profiler.java +++ b/src/main/java/net/vulkanmod/render/profiling/Profiler.java @@ -16,41 +16,33 @@ public class Profiler { private static final float CONVERSION = NANOS_IN_MS; private static final float INV_CONVERSION = 1.0f / CONVERSION; private static final int SAMPLE_COUNT = 200; - - public static boolean ACTIVE = FORCE_ACTIVE; - private static final Profiler MAIN_PROFILER = new Profiler("Main"); - - public static Profiler getMainProfiler() { - return MAIN_PROFILER; - } - - public static void setActive(boolean b) { - if (!FORCE_ACTIVE) - ACTIVE = b; - - } - + public static boolean ACTIVE = FORCE_ACTIVE; private final String name; - LongArrayList startTimes = new LongArrayList(); ObjectArrayList nodeStack = new ObjectArrayList<>(); - ObjectArrayList nodes = new ObjectArrayList<>(); ObjectArrayList currentFrameNodes = new ObjectArrayList<>(); Object2ReferenceOpenHashMap nodeMap = new Object2ReferenceOpenHashMap<>(); - Node mainNode; Node selectedNode; Node currentNode; - ProfilerResults profilerResults = new ProfilerResults(); - public Profiler(String s) { this.name = s; this.currentNode = this.selectedNode = this.mainNode = new Node(s); } + public static Profiler getMainProfiler() { + return MAIN_PROFILER; + } + + public static void setActive(boolean b) { + if (!FORCE_ACTIVE) + ACTIVE = b; + + } + public void push(String s) { if (!(ACTIVE)) return; diff --git a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java index 8f0ffdd9f..ffe9a5d7d 100644 --- a/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java +++ b/src/main/java/net/vulkanmod/render/profiling/ProfilerOverlay.java @@ -1,9 +1,6 @@ package net.vulkanmod.render.profiling; import com.google.common.base.Strings; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; @@ -12,6 +9,7 @@ import net.vulkanmod.render.chunk.WorldRenderer; import net.vulkanmod.render.chunk.build.task.ChunkTask; import net.vulkanmod.render.chunk.build.thread.BuilderResources; +import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.util.ColorUtil; @@ -56,7 +54,6 @@ public static void onKeyPress(int key) { public void render(GuiGraphics guiGraphics) { GuiRenderer.guiGraphics = guiGraphics; - GuiRenderer.pose = guiGraphics.pose(); List infoList = this.buildInfo(); @@ -67,8 +64,7 @@ public void render(GuiGraphics guiGraphics) { Objects.requireNonNull(this.font); - RenderSystem.enableBlend(); - GuiRenderer.beginBatch(); + VRenderSystem.enableBlend(); for (int i = 0; i < infoList.size(); ++i) { String line = infoList.get(i); @@ -81,9 +77,7 @@ public void render(GuiGraphics guiGraphics) { 0, backgroundColor); } } - - GuiRenderer.endBatch(); - RenderSystem.disableBlend(); + VRenderSystem.disableBlend(); for (int i = 0; i < infoList.size(); ++i) { String line = infoList.get(i); @@ -168,4 +162,4 @@ private String getBuildStats() { return String.format("Builders time: %dms avg %dms (%d builds)", totalTime, totalTime / resourcesArray.length, buildCount); } -} \ No newline at end of file +} diff --git a/src/main/java/net/vulkanmod/render/quad/MutableQuadView.java b/src/main/java/net/vulkanmod/render/quad/MutableQuadView.java new file mode 100644 index 000000000..f1c942480 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/quad/MutableQuadView.java @@ -0,0 +1,44 @@ +package net.vulkanmod.render.quad; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.core.Direction; +import net.vulkanmod.render.material.RenderMaterial; +import org.jetbrains.annotations.Nullable; + +public interface MutableQuadView extends QuadView { + int BAKE_LOCK_UV = 1; + int BAKE_NORMALIZED = 1 << 1; + int BAKE_FLIP_U = 1 << 2; + int BAKE_FLIP_V = 1 << 3; + + MutableQuadView pos(int vertexIndex, float x, float y, float z); + + MutableQuadView color(int vertexIndex, int color); + + MutableQuadView uv(int vertexIndex, float u, float v); + + MutableQuadView spriteBake(TextureAtlasSprite sprite, int bakeFlags); + + MutableQuadView lightmap(int vertexIndex, int lightmap); + + MutableQuadView normal(int vertexIndex, float x, float y, float z); + + MutableQuadView cullFace(@Nullable Direction face); + + MutableQuadView nominalFace(@Nullable Direction face); + + MutableQuadView material(RenderMaterial material); + + MutableQuadView colorIndex(int colorIndex); + + MutableQuadView tag(int tag); + + MutableQuadView copyFrom(QuadView quad); + + MutableQuadView fromVanilla(int[] quadData, int startIndex); + + MutableQuadView fromVanilla(BakedQuad quad, RenderMaterial material, @Nullable Direction cullFace); + + MutableQuadView emit(); +} diff --git a/src/main/java/net/vulkanmod/render/quad/QuadView.java b/src/main/java/net/vulkanmod/render/quad/QuadView.java new file mode 100644 index 000000000..dd438881b --- /dev/null +++ b/src/main/java/net/vulkanmod/render/quad/QuadView.java @@ -0,0 +1,69 @@ +package net.vulkanmod.render.quad; + +import net.minecraft.core.Direction; +import net.vulkanmod.render.material.RenderMaterial; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector2f; +import org.joml.Vector3f; + +/** + * Lightweight quad view abstraction used by the new renderer. Derived from the + * Fabric API interface but pared down to the members actually consumed by + * VulkanMod. + */ +public interface QuadView { + int VANILLA_VERTEX_STRIDE = 8; + int VANILLA_QUAD_STRIDE = VANILLA_VERTEX_STRIDE * 4; + + float x(int vertexIndex); + + float y(int vertexIndex); + + float z(int vertexIndex); + + /** + * Returns the position component given a vertex index and axis (0 = X, 1 = Y, 2 = Z). + */ + float posByIndex(int vertexIndex, int coordinateIndex); + + Vector3f copyPos(int vertexIndex, @Nullable Vector3f target); + + int color(int vertexIndex); + + float u(int vertexIndex); + + float v(int vertexIndex); + + Vector2f copyUv(int vertexIndex, @Nullable Vector2f target); + + int lightmap(int vertexIndex); + + boolean hasNormal(int vertexIndex); + + float normalX(int vertexIndex); + + float normalY(int vertexIndex); + + float normalZ(int vertexIndex); + + @Nullable + Vector3f copyNormal(int vertexIndex, @Nullable Vector3f target); + + @Nullable + Direction cullFace(); + + Direction lightFace(); + + @Nullable + Direction nominalFace(); + + Vector3f faceNormal(); + + RenderMaterial material(); + + int colorIndex(); + + int tag(); + + void toVanilla(int[] target, int targetIndex); +} diff --git a/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java index b7b036307..bbe2b4844 100644 --- a/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java +++ b/src/main/java/net/vulkanmod/render/shader/ShaderLoadUtil.java @@ -8,7 +8,10 @@ import net.vulkanmod.vulkan.shader.SPIRVUtils; import org.apache.commons.io.IOUtils; -import java.io.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.FileSystems; @@ -162,7 +165,7 @@ public static String removeNameSpace(String path) { public static String[] splitPath(String path) { int idx = path.lastIndexOf('/'); - return new String[] {path.substring(0, idx), path.substring(idx + 1)}; + return new String[]{path.substring(0, idx), path.substring(idx + 1)}; } public static InputStream getInputStream(String path) { diff --git a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java index 2227c7b22..0d66aa79e 100644 --- a/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java +++ b/src/main/java/net/vulkanmod/render/sky/CloudRenderer.java @@ -1,16 +1,14 @@ package net.vulkanmod.render.sky; import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.*; import net.minecraft.client.CloudStatus; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.FogRenderer; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.world.phys.Vec3; +import net.minecraft.util.ARGB; import net.vulkanmod.render.PipelineManager; import net.vulkanmod.render.VBO; import net.vulkanmod.vulkan.VRenderSystem; @@ -18,6 +16,7 @@ import net.vulkanmod.vulkan.util.ColorUtil; import org.apache.commons.lang3.Validate; import org.joml.Matrix4f; +import org.lwjgl.opengl.GL11; import java.io.IOException; @@ -53,17 +52,44 @@ public CloudRenderer() { loadTexture(); } + private static void putVertex(BufferBuilder bufferBuilder, float x, float y, float z, int color) { + bufferBuilder.addVertex(x, y, z).setColor(color); + } + + private static CloudGrid createCloudGrid(ResourceLocation textureLocation) { + ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); + + try { + Resource resource = resourceManager.getResourceOrThrow(textureLocation); + + try (var inputStream = resource.open()) { + NativeImage image = NativeImage.read(inputStream); + + int width = image.getWidth(); + int height = image.getHeight(); + Validate.isTrue(width == height, "Image width and height must be the same"); + + int[] pixels = image.getPixels(); + + return new CloudGrid(pixels, width); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + public void loadTexture() { this.cloudGrid = createCloudGrid(TEXTURE_LOCATION); } public void renderClouds(ClientLevel level, PoseStack poseStack, Matrix4f modelView, Matrix4f projection, float ticks, float partialTicks, double camX, double camY, double camZ) { - float cloudHeight = level.effects().getCloudHeight(); - - if (Float.isNaN(cloudHeight)) { + var cloudHeightOpt = level.dimensionType().cloudHeight(); + if (cloudHeightOpt.isEmpty()) { return; } + float cloudHeight = cloudHeightOpt.get() + 0.33F; + Minecraft minecraft = Minecraft.getInstance(); double timeOffset = (ticks + partialTicks) * 0.03F; @@ -77,11 +103,9 @@ public void renderClouds(ClientLevel level, PoseStack poseStack, Matrix4f modelV byte yState; if (centerY < -4.0f) { yState = Y_BELOW_CLOUDS; - } - else if (centerY > 0.0f) { + } else if (centerY > 0.0f) { yState = Y_ABOVE_CLOUDS; - } - else { + } else { yState = Y_INSIDE_CLOUDS; } @@ -110,7 +134,7 @@ else if (centerY > 0.0f) { return; } - this.cloudBuffer = new VBO(VertexBuffer.Usage.STATIC); + this.cloudBuffer = new VBO(); this.cloudBuffer.upload(cloudsMesh); } @@ -118,8 +142,6 @@ else if (centerY > 0.0f) { return; } - FogRenderer.levelFogColor(); - float xTranslation = (float) (centerX - (centerCellX * CELL_WIDTH)); float yTranslation = (float) (centerY); float zTranslation = (float) (centerZ - (centerCellZ * CELL_WIDTH)); @@ -130,33 +152,36 @@ else if (centerY > 0.0f) { VRenderSystem.setModelOffset(-xTranslation, 0, -zTranslation); - Vec3 cloudColor = level.getCloudColor(partialTicks); - RenderSystem.setShaderColor((float) cloudColor.x, (float) cloudColor.y, (float) cloudColor.z, 0.8f); + int cloudColor = level.getCloudColor(partialTicks); + float r = ARGB.red(cloudColor) / 255.0F; + float g = ARGB.green(cloudColor) / 255.0F; + float b = ARGB.blue(cloudColor) / 255.0F; + VRenderSystem.setShaderColor(r, g, b, 0.8f); GraphicsPipeline pipeline = PipelineManager.getCloudsPipeline(); - RenderSystem.enableBlend(); - RenderSystem.defaultBlendFunc(); - RenderSystem.enableDepthTest(); + VRenderSystem.enableBlend(); + VRenderSystem.blendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA); + VRenderSystem.enableDepthTest(); boolean fastClouds = this.prevCloudsType == CloudStatus.FAST; boolean insideClouds = yState == Y_INSIDE_CLOUDS; boolean disableCull = insideClouds || (fastClouds && centerY <= 0.0f); if (disableCull) { - RenderSystem.disableCull(); + VRenderSystem.disableCull(); } if (!fastClouds) { - RenderSystem.colorMask(false, false, false, false); + VRenderSystem.colorMask(false, false, false, false); this.cloudBuffer.drawWithShader(poseStack.last().pose(), projection, pipeline); - RenderSystem.colorMask(true, true, true, true); + VRenderSystem.colorMask(true, true, true, true); } this.cloudBuffer.drawWithShader(poseStack.last().pose(), projection, pipeline); - RenderSystem.enableCull(); - RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); + VRenderSystem.enableCull(); + VRenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); VRenderSystem.setModelOffset(0.0f, 0.0f, 0.0f); poseStack.popPose(); @@ -194,25 +219,25 @@ private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerC if ((renderFaces & DIR_POS_Y_BIT) != 0 && cloudY <= 0.0f) { final int color = ColorUtil.ARGB.multiplyRGB(baseColor, upFaceBrightness); putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + CELL_WIDTH, color); - putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, color); - putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + 0.0f, color); - putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, color); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + 0.0f, color); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + CELL_WIDTH, color); } if ((renderFaces & DIR_NEG_Y_BIT) != 0 && cloudY >= -CELL_HEIGHT) { final int color = ColorUtil.ARGB.multiplyRGB(baseColor, downFaceBrightness); - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, color); - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, color); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, color); putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, color); } if ((renderFaces & DIR_POS_X_BIT) != 0 && (x < 1.0f || insideClouds)) { final int color = ColorUtil.ARGB.multiplyRGB(baseColor, xDirBrightness); putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + CELL_WIDTH, color); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, color); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, color); - putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, color); } if ((renderFaces & DIR_NEG_X_BIT) != 0 && (x > -1.0f || insideClouds)) { @@ -225,24 +250,23 @@ private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerC if ((renderFaces & DIR_POS_Z_BIT) != 0 && (z < 1.0f || insideClouds)) { final int color = ColorUtil.ARGB.multiplyRGB(baseColor, zDirBrightness); - putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + CELL_WIDTH, color); - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, color); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, color); putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + CELL_WIDTH, color); } if ((renderFaces & DIR_NEG_Z_BIT) != 0 && (z > -1.0f || insideClouds)) { final int color = ColorUtil.ARGB.multiplyRGB(baseColor, zDirBrightness); putVertex(bufferBuilder, x + CELL_WIDTH, CELL_HEIGHT, z + 0.0f, color); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, color); - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, color); - putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + 0.0f, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + 0.0f, CELL_HEIGHT, z + 0.0f, color); } } } - } - else { + } else { for (int cellX = -renderDistance; cellX < renderDistance; ++cellX) { for (int cellZ = -renderDistance; cellZ < renderDistance; ++cellZ) { @@ -255,9 +279,9 @@ private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerC if ((renderFaces & DIR_NEG_Y_BIT) != 0) { final int color = ColorUtil.ARGB.multiplyRGB(baseColor, upFaceBrightness); - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, color); - putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, color); - putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + CELL_WIDTH, color); + putVertex(bufferBuilder, x + 0.0f, 0.0f, z + 0.0f, color); + putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + 0.0f, color); putVertex(bufferBuilder, x + CELL_WIDTH, 0.0f, z + CELL_WIDTH, color); } @@ -268,32 +292,6 @@ private MeshData buildClouds(Tesselator tesselator, int centerCellX, int centerC return bufferBuilder.build(); } - private static void putVertex(BufferBuilder bufferBuilder, float x, float y, float z, int color) { - bufferBuilder.addVertex(x, y, z).setColor(color); - } - - private static CloudGrid createCloudGrid(ResourceLocation textureLocation) { - ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); - - try { - Resource resource = resourceManager.getResourceOrThrow(textureLocation); - - try (var inputStream = resource.open()) { - NativeImage image = NativeImage.read(inputStream); - - int width = image.getWidth(); - int height = image.getHeight(); - Validate.isTrue(width == height, "Image width and height must be the same"); - - int[] pixels = image.getPixelsRGBA(); - - return new CloudGrid(pixels, width); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } - static class CloudGrid { final int width; final int[] pixels; @@ -306,6 +304,10 @@ static class CloudGrid { this.renderFaces = computeRenderFaces(); } + private static boolean hasColor(int pixel) { + return ((pixel >> 24) & 0xFF) > 1; + } + byte[] computeRenderFaces() { byte[] renderFaces = new byte[pixels.length]; @@ -379,9 +381,5 @@ int getWrappedIdx(int x, int z) { int getIdx(int x, int z) { return z * this.width + x; } - - private static boolean hasColor(int pixel) { - return ((pixel >> 24) & 0xFF) > 1; - } } } diff --git a/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java b/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java index 82f0ceab2..7e3082cc1 100644 --- a/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java +++ b/src/main/java/net/vulkanmod/render/texture/SpriteUpdateUtil.java @@ -9,8 +9,8 @@ public abstract class SpriteUpdateUtil { - private static boolean doUpload = true; private static final Set transitionedLayouts = new HashSet<>(); + private static boolean doUpload = true; public static void setDoUpload(boolean b) { doUpload = b; diff --git a/src/main/java/net/vulkanmod/render/util/DrawUtil.java b/src/main/java/net/vulkanmod/render/util/DrawUtil.java index 430194d69..cc0e0e6dd 100644 --- a/src/main/java/net/vulkanmod/render/util/DrawUtil.java +++ b/src/main/java/net/vulkanmod/render/util/DrawUtil.java @@ -1,10 +1,12 @@ package net.vulkanmod.render.util; +import com.mojang.blaze3d.ProjectionType; +import com.mojang.blaze3d.buffers.GpuBufferSlice; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.*; import net.vulkanmod.vulkan.Renderer; +import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import net.vulkanmod.vulkan.shader.Pipeline; import net.vulkanmod.vulkan.texture.VTextureSelector; import net.vulkanmod.vulkan.texture.VulkanImage; import org.joml.Matrix4f; @@ -12,13 +14,15 @@ public class DrawUtil { + private static final MatrixUniformBuffer PROJECTION_BUFFER = new MatrixUniformBuffer("Vulkan UI Projection"); + public static void blitQuad() { blitQuad(0.0f, 1.0f, 1.0f, 0.0f); } public static void drawTexQuad(BufferBuilder builder, float x0, float y0, float x1, float y1, float z, float u0, float v0, float u1, float v1) { - Tesselator tesselator = RenderSystem.renderThreadTesselator(); + Tesselator tesselator = Tesselator.getInstance(); BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX); bufferBuilder.addVertex(x0, y0, z).setUv(0.0F, 1.0F); bufferBuilder.addVertex(x1, y0, z).setUv(1.0F, 1.0F); @@ -32,7 +36,7 @@ public static void drawTexQuad(BufferBuilder builder, float x0, float y0, float } public static void blitQuad(float x0, float y0, float x1, float y1) { - Tesselator tesselator = RenderSystem.renderThreadTesselator(); + Tesselator tesselator = Tesselator.getInstance(); BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX); bufferBuilder.addVertex(x0, y0, 0.0f).setUv(0.0F, 1.0F); bufferBuilder.addVertex(x1, y0, 0.0f).setUv(1.0F, 1.0F); @@ -52,11 +56,13 @@ public static void drawFramebuffer(GraphicsPipeline pipeline, VulkanImage attach VTextureSelector.bindTexture(attachment); Matrix4f matrix4f = new Matrix4f().setOrtho(0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, true); - RenderSystem.setProjectionMatrix(matrix4f, VertexSorting.DISTANCE_TO_ORIGIN); + GpuBufferSlice projectionSlice = PROJECTION_BUFFER.upload(matrix4f); + RenderSystem.setProjectionMatrix(projectionSlice, ProjectionType.ORTHOGRAPHIC); Matrix4fStack posestack = RenderSystem.getModelViewStack(); posestack.pushMatrix(); posestack.identity(); - RenderSystem.applyModelViewMatrix(); + VRenderSystem.applyModelViewMatrix(new Matrix4f(posestack)); + VRenderSystem.calculateMVP(); posestack.popMatrix(); Renderer.getInstance().uploadAndBindUBOs(pipeline); diff --git a/src/main/java/net/vulkanmod/render/util/MatrixUniformBuffer.java b/src/main/java/net/vulkanmod/render/util/MatrixUniformBuffer.java new file mode 100644 index 000000000..58a01e774 --- /dev/null +++ b/src/main/java/net/vulkanmod/render/util/MatrixUniformBuffer.java @@ -0,0 +1,35 @@ +package net.vulkanmod.render.util; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.buffers.GpuBufferSlice; +import com.mojang.blaze3d.buffers.Std140Builder; +import com.mojang.blaze3d.systems.RenderSystem; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; +import org.lwjgl.system.MemoryStack; + +import java.nio.ByteBuffer; + +public final class MatrixUniformBuffer implements AutoCloseable { + private final GpuBuffer buffer; + private final GpuBufferSlice slice; + + public MatrixUniformBuffer(String debugName) { + this.buffer = RenderSystem.getDevice().createBuffer(() -> debugName, 136, RenderSystem.PROJECTION_MATRIX_UBO_SIZE); + this.slice = this.buffer.slice(0, RenderSystem.PROJECTION_MATRIX_UBO_SIZE); + } + + public GpuBufferSlice upload(Matrix4f matrix) { + try (MemoryStack stack = MemoryStack.stackPush()) { + ByteBuffer data = Std140Builder.onStack(stack, RenderSystem.PROJECTION_MATRIX_UBO_SIZE).putMat4f((Matrix4fc) matrix).get(); + RenderSystem.getDevice().createCommandEncoder().writeToBuffer(this.buffer.slice(), data); + } + return this.slice; + } + + @Override + public void close() { + this.buffer.close(); + } +} + diff --git a/src/main/java/net/vulkanmod/render/util/SortUtil.java b/src/main/java/net/vulkanmod/render/util/SortUtil.java index ef524b6ce..08f6150b5 100644 --- a/src/main/java/net/vulkanmod/render/util/SortUtil.java +++ b/src/main/java/net/vulkanmod/render/util/SortUtil.java @@ -23,13 +23,12 @@ public static void mergeSort(int[] indices, float[] distances, int from, int to, if (Float.compare(distances[supp[mid]], distances[supp[mid - 1]]) <= 0) { System.arraycopy(supp, from, indices, from, len); - } - else { + } else { int i = from; int p = from; - for(int q = mid; i < to; ++i) { - if (q < to && (p >= mid || Float.compare(distances[supp[q]], distances[supp[p]]) > 0)) { + for (int q = mid; i < to; ++i) { + if (q < to && (p >= mid || Float.compare(distances[supp[q]], distances[supp[p]]) > 0)) { indices[i] = supp[q++]; } else { indices[i] = supp[p++]; @@ -68,33 +67,31 @@ public static void quickSort(int[] is, float[] distances, int from, int to) { swap(is, m, d); float mValue = distances[v]; - while(true) { + while (true) { - while(b < c) { - if(Float.compare(distances[is[b]], mValue) > 0) { - while(b < c) { - if(Float.compare(distances[is[c]], mValue) < 0) { + while (b < c) { + if (Float.compare(distances[is[b]], mValue) > 0) { + while (b < c) { + if (Float.compare(distances[is[c]], mValue) < 0) { swap(is, b, c); b++; c--; break; - } - else { + } else { c--; } } - } - else { + } else { b++; } } swap(is, d, b); - if(b - a > 1) + if (b - a > 1) quickSort(is, distances, a, b); - if(d - b > 1) + if (d - b > 1) quickSort(is, distances, b, d); return; @@ -106,7 +103,7 @@ public static void quickSort(int[] is, float[] distances, int from, int to) { private static void insertionSort(int[] is, float[] distances, int from, int to) { int i = from; - while(true) { + while (true) { ++i; if (i >= to) { return; @@ -115,7 +112,7 @@ private static void insertionSort(int[] is, float[] distances, int from, int to) int t = is[i]; int j = i; - for(int u = is[i - 1]; Float.compare(distances[u], distances[t]) < 0; u = is[j - 1]) { + for (int u = is[i - 1]; Float.compare(distances[u], distances[t]) < 0; u = is[j - 1]) { is[j] = u; if (from == j - 1) { --j; @@ -130,7 +127,7 @@ private static void insertionSort(int[] is, float[] distances, int from, int to) } public static void swap(int[] x, int a, int b, int n) { - for(int i = 0; i < n; ++b, ++i, ++a) { + for (int i = 0; i < n; ++b, ++i, ++a) { swap(x, a, b); } diff --git a/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java b/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java index 437345ff8..8c32da15f 100644 --- a/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java +++ b/src/main/java/net/vulkanmod/render/vertex/CustomVertexFormat.java @@ -5,16 +5,16 @@ public class CustomVertexFormat { - public static final VertexFormatElement ELEMENT_POSITION = new VertexFormatElement(0, 0,VertexFormatElement.Type.SHORT, VertexFormatElement.Usage.POSITION, 4); + public static final VertexFormatElement ELEMENT_POSITION = new VertexFormatElement(0, 0, VertexFormatElement.Type.SHORT, VertexFormatElement.Usage.POSITION, 4); public static final VertexFormatElement ELEMENT_COLOR = new VertexFormatElement(1, 0, VertexFormatElement.Type.UINT, VertexFormatElement.Usage.COLOR, 1); public static final VertexFormatElement ELEMENT_UV0 = new VertexFormatElement(2, 0, VertexFormatElement.Type.USHORT, VertexFormatElement.Usage.UV, 2); public static final VertexFormat COMPRESSED_TERRAIN = VertexFormat.builder() - .add("Position", ELEMENT_POSITION) - .add("UV0", ELEMENT_UV0) - .add("Color", ELEMENT_COLOR) - .build(); + .add("Position", ELEMENT_POSITION) + .add("UV0", ELEMENT_UV0) + .add("Color", ELEMENT_COLOR) + .build(); public static final VertexFormat NONE = VertexFormat.builder().build(); -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java b/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java index 9e8651dae..24003226f 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainBufferBuilder.java @@ -11,16 +11,12 @@ public class TerrainBufferBuilder implements VertexConsumer { private static final Logger LOGGER = Initializer.LOGGER; private static final MemoryUtil.MemoryAllocator ALLOCATOR = MemoryUtil.getAllocator(false); - - private int capacity; - private int vertexSize; - protected long bufferPtr; - protected int nextElementByte; int vertices; - - private long elementPtr; + private int capacity; + private int vertexSize; + private long elementPtr; private VertexBuilder vertexBuilder; @@ -88,54 +84,54 @@ public int getNextElementByte() { return nextElementByte; } - @Override - public VertexConsumer addVertex(float x, float y, float z) { - this.elementPtr = this.bufferPtr + this.nextElementByte; - this.endVertex(); + @Override + public VertexConsumer addVertex(float x, float y, float z) { + this.elementPtr = this.bufferPtr + this.nextElementByte; + this.endVertex(); - this.vertexBuilder.position(this.elementPtr, x, y, z); + this.vertexBuilder.position(this.elementPtr, x, y, z); - return this; - } + return this; + } - @Override - public VertexConsumer setColor(int r, int g, int b, int a) { - int color = (a & 0xFF) << 24 | (b & 0xFF) << 16 | (g & 0xFF) << 8 | (r & 0xFF); + @Override + public VertexConsumer setColor(int r, int g, int b, int a) { + int color = (a & 0xFF) << 24 | (b & 0xFF) << 16 | (g & 0xFF) << 8 | (r & 0xFF); - this.vertexBuilder.color(this.elementPtr, color); + this.vertexBuilder.color(this.elementPtr, color); - return this; - } + return this; + } - @Override - public VertexConsumer setUv(float u, float v) { - this.vertexBuilder.uv(this.elementPtr, u, v); + @Override + public VertexConsumer setUv(float u, float v) { + this.vertexBuilder.uv(this.elementPtr, u, v); - return this; - } + return this; + } - public VertexConsumer setLight(int i) { - this.vertexBuilder.light(this.elementPtr, i); + public VertexConsumer setLight(int i) { + this.vertexBuilder.light(this.elementPtr, i); - return this; - } + return this; + } - @Override - public VertexConsumer setNormal(float f, float g, float h) { - int packedNormal = I32_SNorm.packNormal(f, g, h); + @Override + public VertexConsumer setNormal(float f, float g, float h) { + int packedNormal = I32_SNorm.packNormal(f, g, h); - this.vertexBuilder.normal(this.elementPtr, packedNormal); + this.vertexBuilder.normal(this.elementPtr, packedNormal); - return this; - } + return this; + } - @Override - public VertexConsumer setUv1(int i, int j) { - return this; - } + @Override + public VertexConsumer setUv1(int i, int j) { + return this; + } - @Override - public VertexConsumer setUv2(int i, int j) { - return this; - } + @Override + public VertexConsumer setUv2(int i, int j) { + return this; + } } diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java index f12c69a17..188604ca2 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainBuilder.java @@ -13,25 +13,17 @@ public class TerrainBuilder { private static final Logger LOGGER = Initializer.LOGGER; private static final MemoryUtil.MemoryAllocator ALLOCATOR = MemoryUtil.getAllocator(false); - + private final VertexFormat format; + private final QuadSorter quadSorter = new QuadSorter(); + private final TerrainBufferBuilder[] bufferBuilders; protected long indexBufferPtr; - - private int indexBufferCapacity; protected long bufferPtr; - - private final VertexFormat format; - + protected VertexBuilder vertexBuilder; + private int indexBufferCapacity; private boolean building; - - private final QuadSorter quadSorter = new QuadSorter(); - private boolean needsSorting; private boolean indexOnly; - protected VertexBuilder vertexBuilder; - - private final TerrainBufferBuilder[] bufferBuilders; - public TerrainBuilder(int size) { // TODO index buffer this.indexBufferPtr = ALLOCATOR.malloc(size); diff --git a/src/main/java/net/vulkanmod/render/vertex/TerrainRenderType.java b/src/main/java/net/vulkanmod/render/vertex/TerrainRenderType.java index 2eb1a14d0..4d58649bb 100644 --- a/src/main/java/net/vulkanmod/render/vertex/TerrainRenderType.java +++ b/src/main/java/net/vulkanmod/render/vertex/TerrainRenderType.java @@ -1,6 +1,7 @@ package net.vulkanmod.render.vertex; import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.chunk.ChunkSectionLayer; import net.vulkanmod.Initializer; import net.vulkanmod.interfaces.ExtendedRenderType; import net.vulkanmod.vulkan.VRenderSystem; @@ -37,12 +38,8 @@ public enum TerrainRenderType { this.alphaCutout = alphaCutout; } - public void setCutoutUniform() { - VRenderSystem.alphaCutout = this.alphaCutout; - } - public static TerrainRenderType get(RenderType renderType) { - return ((ExtendedRenderType)renderType).getTerrainRenderType(); + return ((ExtendedRenderType) renderType).getTerrainRenderType(); } public static TerrainRenderType get(String name) { @@ -56,12 +53,22 @@ public static TerrainRenderType get(String name) { }; } + public static TerrainRenderType fromChunkLayer(ChunkSectionLayer layer) { + return switch (layer) { + case SOLID -> SOLID; + case CUTOUT -> CUTOUT; + case CUTOUT_MIPPED -> CUTOUT_MIPPED; + case TRANSLUCENT -> TRANSLUCENT; + case TRIPWIRE -> TRIPWIRE; + }; + } + public static RenderType getRenderType(TerrainRenderType renderType) { return switch (renderType) { case SOLID -> RenderType.solid(); case CUTOUT -> RenderType.cutout(); case CUTOUT_MIPPED -> RenderType.cutoutMipped(); - case TRANSLUCENT -> RenderType.translucent(); + case TRANSLUCENT -> RenderType.translucentMovingBlock(); case TRIPWIRE -> RenderType.tripwire(); }; } @@ -84,4 +91,8 @@ public static void updateMapping() { public static TerrainRenderType getRemapped(TerrainRenderType renderType) { return remapper.apply(renderType); } + + public void setCutoutUniform() { + VRenderSystem.alphaCutout = this.alphaCutout; + } } diff --git a/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java b/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java index 5f6555459..459ab9531 100644 --- a/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java +++ b/src/main/java/net/vulkanmod/render/vertex/VertexBuilder.java @@ -69,13 +69,11 @@ public int getStride() { } class CompressedVertexBuilder implements VertexBuilder { - private static final int VERTEX_SIZE = 16; - public static final float POS_CONV_MUL = 2048.0f; public static final float POS_OFFSET = -4.0f; public static final float POS_OFFSET_CONV = POS_OFFSET * POS_CONV_MUL; - public static final float UV_CONV_MUL = 32768.0f; + private static final int VERTEX_SIZE = 16; public void vertex(long ptr, float x, float y, float z, int color, float u, float v, int light, int packedNormal) { final short sX = (short) (x * POS_CONV_MUL + POS_OFFSET_CONV); diff --git a/src/main/java/net/vulkanmod/render/vertex/format/I32_SNorm.java b/src/main/java/net/vulkanmod/render/vertex/format/I32_SNorm.java index fb8366991..e1e4923d2 100644 --- a/src/main/java/net/vulkanmod/render/vertex/format/I32_SNorm.java +++ b/src/main/java/net/vulkanmod/render/vertex/format/I32_SNorm.java @@ -8,22 +8,22 @@ public static int packNormal(float x, float y, float z) { y *= 127.0f; z *= 127.0f; - return ((int)x & 0xFF) | ((int)y & 0xFF) << 8| ((int)z & 0xFF) << 16; + return ((int) x & 0xFF) | ((int) y & 0xFF) << 8 | ((int) z & 0xFF) << 16; } public static int packNormal(int x, int y, int z) { - return (x & 0xFF) | (y & 0xFF) << 8| (z & 0xFF) << 16; + return (x & 0xFF) | (y & 0xFF) << 8 | (z & 0xFF) << 16; } public static float unpackX(int i) { - return (byte)(i & 0xFF) * NORM_INV; + return (byte) (i & 0xFF) * NORM_INV; } public static float unpackY(int i) { - return (byte)((i >> 8) & 0xFF) * NORM_INV; + return (byte) ((i >> 8) & 0xFF) * NORM_INV; } public static float unpackZ(int i) { - return (byte)((i >> 16) & 0xFF) * NORM_INV; + return (byte) ((i >> 16) & 0xFF) * NORM_INV; } } diff --git a/src/main/java/net/vulkanmod/util/TriState.java b/src/main/java/net/vulkanmod/util/TriState.java new file mode 100644 index 000000000..56cf640cf --- /dev/null +++ b/src/main/java/net/vulkanmod/util/TriState.java @@ -0,0 +1,22 @@ +package net.vulkanmod.util; + +/** + * Minimal tri-state representation used by VulkanMod's rendering helpers. + */ +public enum TriState { + DEFAULT, + TRUE, + FALSE; + + public boolean isDefault() { + return this == DEFAULT; + } + + public boolean isTrue() { + return this == TRUE; + } + + public boolean isFalse() { + return this == FALSE; + } +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/vulkan/Drawer.java b/src/main/java/net/vulkanmod/vulkan/Drawer.java index fd2ae33f8..753179351 100644 --- a/src/main/java/net/vulkanmod/vulkan/Drawer.java +++ b/src/main/java/net/vulkanmod/vulkan/Drawer.java @@ -1,7 +1,8 @@ package net.vulkanmod.vulkan; import com.mojang.blaze3d.vertex.VertexFormat; -import net.vulkanmod.vulkan.memory.*; +import net.vulkanmod.vulkan.memory.MemoryManager; +import net.vulkanmod.vulkan.memory.MemoryTypes; import net.vulkanmod.vulkan.memory.buffer.Buffer; import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; import net.vulkanmod.vulkan.memory.buffer.UniformBuffer; @@ -26,18 +27,15 @@ public class Drawer { private static final LongBuffer offsets = MemoryUtil.memAllocLong(1); private static final long pBuffers = MemoryUtil.memAddress0(buffers); private static final long pOffsets = MemoryUtil.memAddress0(offsets); - - private int framesNum; - private VertexBuffer[] vertexBuffers; - private IndexBuffer[] indexBuffers; - private final AutoIndexBuffer quadsIndexBuffer; private final AutoIndexBuffer quadsIntIndexBuffer; private final AutoIndexBuffer linesIndexBuffer; private final AutoIndexBuffer debugLineStripIndexBuffer; private final AutoIndexBuffer triangleFanIndexBuffer; private final AutoIndexBuffer triangleStripIndexBuffer; - + private int framesNum; + private VertexBuffer[] vertexBuffers; + private IndexBuffer[] indexBuffers; private UniformBuffer[] uniformBuffers; private int currentFrame; @@ -60,28 +58,22 @@ public void createResources(int framesNum) { this.framesNum = framesNum; if (this.vertexBuffers != null) { - Arrays.stream(this.vertexBuffers).iterator().forEachRemaining( - Buffer::scheduleFree - ); + Arrays.stream(this.vertexBuffers).iterator().forEachRemaining(Buffer::scheduleFree); } this.vertexBuffers = new VertexBuffer[framesNum]; - Arrays.setAll(this.vertexBuffers, i -> new VertexBuffer(INITIAL_VB_SIZE, MemoryTypes.HOST_MEM)); + Arrays.setAll(this.vertexBuffers, _ -> new VertexBuffer(INITIAL_VB_SIZE, MemoryTypes.HOST_MEM)); if (this.indexBuffers != null) { - Arrays.stream(this.indexBuffers).iterator().forEachRemaining( - Buffer::scheduleFree - ); + Arrays.stream(this.indexBuffers).iterator().forEachRemaining(Buffer::scheduleFree); } this.indexBuffers = new IndexBuffer[framesNum]; - Arrays.setAll(this.indexBuffers, i -> new IndexBuffer(INITIAL_IB_SIZE, MemoryTypes.HOST_MEM)); + Arrays.setAll(this.indexBuffers, _ -> new IndexBuffer(INITIAL_IB_SIZE, MemoryTypes.HOST_MEM)); if (this.uniformBuffers != null) { - Arrays.stream(this.uniformBuffers).iterator().forEachRemaining( - Buffer::scheduleFree - ); + Arrays.stream(this.uniformBuffers).iterator().forEachRemaining(Buffer::scheduleFree); } this.uniformBuffers = new UniformBuffer[framesNum]; - Arrays.setAll(this.uniformBuffers, i -> new UniformBuffer(INITIAL_UB_SIZE, MemoryTypes.HOST_MEM)); + Arrays.setAll(this.uniformBuffers, _ -> new UniformBuffer(INITIAL_UB_SIZE, MemoryTypes.HOST_MEM)); } public void resetBuffers(int currentFrame) { @@ -106,8 +98,7 @@ public void draw(ByteBuffer vertexData, ByteBuffer indexData, VertexFormat.Mode int indexCount = vertexCount * 3 / 2; drawIndexed(vertexBuffer, indexBuffer, indexCount); - } - else { + } else { AutoIndexBuffer autoIndexBuffer = getAutoIndexBuffer(mode, vertexCount); if (autoIndexBuffer != null) { @@ -115,22 +106,21 @@ public void draw(ByteBuffer vertexData, ByteBuffer indexData, VertexFormat.Mode autoIndexBuffer.checkCapacity(indexCount); drawIndexed(vertexBuffer, autoIndexBuffer.getIndexBuffer(), indexCount); - } - else { + } else { draw(vertexBuffer, vertexCount); } } } public void drawIndexed(Buffer vertexBuffer, IndexBuffer indexBuffer, int indexCount) { - drawIndexed(vertexBuffer, indexBuffer, indexCount, indexBuffer.indexType.value); + drawIndexed(vertexBuffer, indexBuffer, indexCount, indexBuffer.indexType.value); } public void drawIndexed(Buffer vertexBuffer, Buffer indexBuffer, int indexCount, int indexType) { VkCommandBuffer commandBuffer = Renderer.getCommandBuffer(); - VUtil.UNSAFE.putLong(pBuffers, vertexBuffer.getId()); - VUtil.UNSAFE.putLong(pOffsets, vertexBuffer.getOffset()); + VUtil.putLong(pBuffers, vertexBuffer.getId()); + VUtil.putLong(pOffsets, vertexBuffer.getOffset()); nvkCmdBindVertexBuffers(commandBuffer, 0, 1, pBuffers, pOffsets); bindIndexBuffer(commandBuffer, indexBuffer, indexType); @@ -140,8 +130,8 @@ public void drawIndexed(Buffer vertexBuffer, Buffer indexBuffer, int indexCount, public void draw(VertexBuffer vertexBuffer, int vertexCount) { VkCommandBuffer commandBuffer = Renderer.getCommandBuffer(); - VUtil.UNSAFE.putLong(pBuffers, vertexBuffer.getId()); - VUtil.UNSAFE.putLong(pOffsets, vertexBuffer.getOffset()); + VUtil.putLong(pBuffers, vertexBuffer.getId()); + VUtil.putLong(pOffsets, vertexBuffer.getOffset()); nvkCmdBindVertexBuffers(commandBuffer, 0, 1, pBuffers, pOffsets); vkCmdDraw(commandBuffer, vertexCount, 1, 0, 0); @@ -201,14 +191,13 @@ public AutoIndexBuffer getAutoIndexBuffer(VertexFormat.Mode mode, int vertexCoun case QUADS -> { int indexCount = vertexCount * 3 / 2; - yield indexCount > AutoIndexBuffer.U16_MAX_VERTEX_COUNT - ? this.quadsIntIndexBuffer : this.quadsIndexBuffer; + yield indexCount > AutoIndexBuffer.U16_MAX_VERTEX_COUNT ? this.quadsIntIndexBuffer : this.quadsIndexBuffer; } case LINES -> this.linesIndexBuffer; case TRIANGLE_FAN -> this.triangleFanIndexBuffer; case TRIANGLE_STRIP, LINE_STRIP -> this.triangleStripIndexBuffer; case DEBUG_LINE_STRIP -> this.debugLineStripIndexBuffer; case TRIANGLES, DEBUG_LINES -> null; - }; + }; } } diff --git a/src/main/java/net/vulkanmod/vulkan/Renderer.java b/src/main/java/net/vulkanmod/vulkan/Renderer.java index 45267dcb4..0fe619572 100644 --- a/src/main/java/net/vulkanmod/vulkan/Renderer.java +++ b/src/main/java/net/vulkanmod/vulkan/Renderer.java @@ -1,6 +1,8 @@ package net.vulkanmod.vulkan; -import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.opengl.GlStateManager; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.vertex.VertexFormat; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import net.minecraft.client.Minecraft; @@ -19,19 +21,18 @@ import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.pass.DefaultMainPass; import net.vulkanmod.vulkan.pass.MainPass; -import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import net.vulkanmod.vulkan.shader.Pipeline; -import net.vulkanmod.vulkan.shader.PipelineState; -import net.vulkanmod.vulkan.shader.Uniforms; +import net.vulkanmod.vulkan.shader.*; import net.vulkanmod.vulkan.shader.layout.PushConstants; import net.vulkanmod.vulkan.texture.VTextureSelector; import net.vulkanmod.vulkan.util.VUtil; import net.vulkanmod.vulkan.util.VkResult; -import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryUtil; import org.lwjgl.vulkan.*; +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; @@ -39,8 +40,8 @@ import java.util.List; import java.util.Set; -import static com.mojang.blaze3d.platform.GlConst.GL_COLOR_BUFFER_BIT; -import static com.mojang.blaze3d.platform.GlConst.GL_DEPTH_BUFFER_BIT; +import static com.mojang.blaze3d.opengl.GlConst.GL_COLOR_BUFFER_BIT; +import static com.mojang.blaze3d.opengl.GlConst.GL_DEPTH_BUFFER_BIT; import static net.vulkanmod.vulkan.Vulkan.*; import static org.lwjgl.system.MemoryStack.stackPush; import static org.lwjgl.vulkan.EXTDebugUtils.*; @@ -48,12 +49,37 @@ import static org.lwjgl.vulkan.VK10.*; public class Renderer { + public static boolean skipRendering = false; private static Renderer INSTANCE; - private static VkDevice device; - private static boolean swapChainUpdate = false; - public static boolean skipRendering = false; + private static int currentFrame = 0; + private static int imageIndex; + private static int lastReset = -1; + private final Set usedPipelines = new ObjectOpenHashSet<>(); + private final List onResizeCallbacks = new ObjectArrayList<>(); + MainPass mainPass; + private Pipeline boundPipeline; + private long boundPipelineHandle; + + private Drawer drawer; + + private SwapChain swapChain; + + private int framesNum; + private List commandBuffers; + private ArrayList imageAvailableSemaphores; + private ArrayList renderFinishedSemaphores; + private ArrayList inFlightFences; + + private Framebuffer boundFramebuffer; + private RenderPass boundRenderPass; + private VkCommandBuffer currentCmdBuffer; + private boolean recordingCmds = false; + public Renderer() { + device = Vulkan.getVkDevice(); + framesNum = Initializer.CONFIG.frameQueueSize; + } public static void initRenderer() { INSTANCE = new Renderer(); @@ -76,43 +102,222 @@ public static int getCurrentImage() { return imageIndex; } - private final Set usedPipelines = new ObjectOpenHashSet<>(); - private Pipeline boundPipeline; - private long boundPipelineHandle; + public static void setLineWidth(float width) { + if (INSTANCE.boundFramebuffer == null) { + return; + } + vkCmdSetLineWidth(INSTANCE.currentCmdBuffer, width); + } - private Drawer drawer; + private static void resetDynamicState(VkCommandBuffer commandBuffer) { + vkCmdSetDepthBias(commandBuffer, 0.0F, 0.0F, 0.0F); - private SwapChain swapChain; + vkCmdSetLineWidth(commandBuffer, 1.0F); + } - private int framesNum; - private List commandBuffers; - private ArrayList imageAvailableSemaphores; - private ArrayList renderFinishedSemaphores; - private ArrayList inFlightFences; + public static void setDepthBias(float constant, float slope) { + VkCommandBuffer commandBuffer = INSTANCE.currentCmdBuffer; - private Framebuffer boundFramebuffer; - private RenderPass boundRenderPass; + vkCmdSetDepthBias(commandBuffer, constant, 0.0f, slope); + } - private static int currentFrame = 0; - private static int imageIndex; - private static int lastReset = -1; - private VkCommandBuffer currentCmdBuffer; - private boolean recordingCmds = false; + public static void clearAttachments(int v) { + Framebuffer framebuffer = Renderer.getInstance().boundFramebuffer; + if (framebuffer == null) return; - MainPass mainPass; + clearAttachments(v, framebuffer.getWidth(), framebuffer.getHeight()); + } - private final List onResizeCallbacks = new ObjectArrayList<>(); + public static void clearAttachments(int v, int width, int height) { + if (skipRendering) return; + + try (Arena arena = Arena.ofConfined()) { + VkClearValue colorValue = VUtil.struct( + arena, + VkClearValue.SIZEOF, + VkClearValue.ALIGNOF, + VkClearValue::create + ); + float clearR = VRenderSystem.clearColor.get(0); + float clearG = VRenderSystem.clearColor.get(1); + float clearB = VRenderSystem.clearColor.get(2); + float clearA = VRenderSystem.clearColor.get(3); + colorValue.color().float32(0, clearR); + colorValue.color().float32(1, clearG); + colorValue.color().float32(2, clearB); + colorValue.color().float32(3, clearA); + + VkClearValue depthValue = VUtil.struct( + arena, + VkClearValue.SIZEOF, + VkClearValue.ALIGNOF, + VkClearValue::create + ); + depthValue.depthStencil().set(VRenderSystem.clearDepthValue, 0); - public Renderer() { - device = Vulkan.getVkDevice(); - framesNum = Initializer.CONFIG.frameQueueSize; + int attachmentsCount = v == (GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT) ? 2 : 1; + VkClearAttachment.Buffer attachments = VUtil.structBuffer( + arena, + VkClearAttachment.SIZEOF, + VkClearAttachment.ALIGNOF, + attachmentsCount, + VkClearAttachment::create + ); + + switch (v) { + case GL_DEPTH_BUFFER_BIT -> { + VkClearAttachment clearDepth = attachments.get(0); + clearDepth.aspectMask(VK_IMAGE_ASPECT_DEPTH_BIT); + clearDepth.colorAttachment(0); + clearDepth.clearValue(depthValue); + } + case GL_COLOR_BUFFER_BIT -> { + VkClearAttachment clearColor = attachments.get(0); + clearColor.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT); + clearColor.colorAttachment(0); + clearColor.clearValue(colorValue); + } + case GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT -> { + VkClearAttachment clearColor = attachments.get(0); + clearColor.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT); + clearColor.colorAttachment(0); + clearColor.clearValue(colorValue); + + VkClearAttachment clearDepth = attachments.get(1); + clearDepth.aspectMask(VK_IMAGE_ASPECT_DEPTH_BIT); + clearDepth.colorAttachment(0); + clearDepth.clearValue(depthValue); + } + default -> throw new RuntimeException("unexpected value"); + } + + VkClearRect.Buffer rect = VUtil.structBuffer( + arena, + VkClearRect.SIZEOF, + VkClearRect.ALIGNOF, + 1, + VkClearRect::create + ); + rect.get(0).rect().offset().set(0, 0); + rect.get(0).rect().extent().set(width, height); + rect.get(0).baseArrayLayer(0); + rect.get(0).layerCount(1); + + vkCmdClearAttachments(INSTANCE.currentCmdBuffer, attachments, rect); + } } - public static void setLineWidth(float width) { - if (INSTANCE.boundFramebuffer == null) { - return; + public static void setInvertedViewport(int x, int y, int width, int height) { + setViewportState(x, y + height, width, -height); + } + + public static void resetViewport() { + int width = INSTANCE.getSwapChain().getWidth(); + int height = INSTANCE.getSwapChain().getHeight(); + + setViewportState(0, 0, width, height); + } + + public static void setViewportState(int x, int y, int width, int height) { + GlStateManager._viewport(x, y, width, height); + } + + public static void setViewport(int x, int y, int width, int height) { + if (!INSTANCE.recordingCmds) return; + + try (Arena arena = Arena.ofConfined()) { + VkViewport.Buffer viewport = VUtil.structBuffer( + arena, + VkViewport.SIZEOF, + VkViewport.ALIGNOF, + 1, + VkViewport::create + ); + viewport.x(x); + viewport.y(height + y); + viewport.width(width); + viewport.height(-height); + viewport.minDepth(0.0f); + viewport.maxDepth(1.0f); + + vkCmdSetViewport(INSTANCE.currentCmdBuffer, 0, viewport); } - vkCmdSetLineWidth(INSTANCE.currentCmdBuffer, width); + } + + public static void setScissor(int x, int y, int width, int height) { + if (INSTANCE.boundFramebuffer == null) return; + + try (Arena arena = Arena.ofConfined()) { + int framebufferHeight = INSTANCE.boundFramebuffer.getHeight(); + + x = Math.max(0, x); + + VkRect2D.Buffer scissor = VUtil.structBuffer( + arena, + VkRect2D.SIZEOF, + VkRect2D.ALIGNOF, + 1, + VkRect2D::create + ); + scissor.offset().set(x, framebufferHeight - (y + height)); + scissor.extent().set(width, height); + + vkCmdSetScissor(INSTANCE.currentCmdBuffer, 0, scissor); + } + } + + public static void resetScissor() { + if (INSTANCE.boundFramebuffer == null) return; + + INSTANCE.boundFramebuffer.applyScissor(INSTANCE.currentCmdBuffer); + } + + public static void pushDebugSection(String s) { + if (Vulkan.ENABLE_VALIDATION_LAYERS) { + VkCommandBuffer commandBuffer = INSTANCE.currentCmdBuffer; + + try (Arena arena = Arena.ofConfined()) { + VkDebugUtilsLabelEXT markerInfo = VUtil.struct( + arena, + VkDebugUtilsLabelEXT.SIZEOF, + VkDebugUtilsLabelEXT.ALIGNOF, + VkDebugUtilsLabelEXT::create + ); + markerInfo.sType(VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT); + ByteBuffer label = VUtil.utf8String(arena, s); + markerInfo.pLabelName(label); + vkCmdBeginDebugUtilsLabelEXT(commandBuffer, markerInfo); + } + } + } + + public static void popDebugSection() { + if (Vulkan.ENABLE_VALIDATION_LAYERS) { + VkCommandBuffer commandBuffer = INSTANCE.currentCmdBuffer; + + vkCmdEndDebugUtilsLabelEXT(commandBuffer); + } + } + + public static void popPushDebugSection(String s) { + popDebugSection(); + pushDebugSection(s); + } + + public static int getFramesNum() { + return INSTANCE.framesNum; + } + + public static VkCommandBuffer getCommandBuffer() { + return INSTANCE.currentCmdBuffer; + } + + public static boolean isRecording() { + return INSTANCE.recordingCmds; + } + + public static void scheduleSwapChainUpdate() { + swapChainUpdate = true; } private void init() { @@ -140,23 +345,30 @@ private void allocateCommandBuffers() { commandBuffers = new ArrayList<>(framesNum); - try (MemoryStack stack = stackPush()) { - - VkCommandBufferAllocateInfo allocInfo = VkCommandBufferAllocateInfo.calloc(stack); + try (Arena arena = Arena.ofConfined()) { + VkCommandBufferAllocateInfo allocInfo = VUtil.struct( + arena, + VkCommandBufferAllocateInfo.SIZEOF, + VkCommandBufferAllocateInfo.ALIGNOF, + VkCommandBufferAllocateInfo::create + ); allocInfo.sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO); allocInfo.commandPool(getCommandPool()); allocInfo.level(VK_COMMAND_BUFFER_LEVEL_PRIMARY); allocInfo.commandBufferCount(framesNum); - PointerBuffer pCommandBuffers = stack.mallocPointer(framesNum); + MemorySegment pCommandBuffers = arena.allocate(ValueLayout.ADDRESS, framesNum); - int vkResult = vkAllocateCommandBuffers(device, allocInfo, pCommandBuffers); + int vkResult = VK10.nvkAllocateCommandBuffers(device, allocInfo.address(), pCommandBuffers.address()); if (vkResult != VK_SUCCESS) { throw new RuntimeException("Failed to allocate command buffers: %s".formatted(VkResult.decode(vkResult))); } + long stride = ValueLayout.ADDRESS.byteSize(); for (int i = 0; i < framesNum; i++) { - commandBuffers.add(new VkCommandBuffer(pCommandBuffers.get(i), device)); + MemorySegment handleSegment = pCommandBuffers.get(ValueLayout.ADDRESS, (long) i * stride); + long handle = handleSegment.address(); + commandBuffers.add(new VkCommandBuffer(handle, device)); } } } @@ -166,34 +378,39 @@ private void createSyncObjects() { renderFinishedSemaphores = new ArrayList<>(framesNum); inFlightFences = new ArrayList<>(framesNum); - try (MemoryStack stack = stackPush()) { - - VkSemaphoreCreateInfo semaphoreInfo = VkSemaphoreCreateInfo.calloc(stack); + try (Arena arena = Arena.ofConfined()) { + VkSemaphoreCreateInfo semaphoreInfo = VUtil.struct( + arena, + VkSemaphoreCreateInfo.SIZEOF, + VkSemaphoreCreateInfo.ALIGNOF, + VkSemaphoreCreateInfo::create + ); semaphoreInfo.sType(VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO); - VkFenceCreateInfo fenceInfo = VkFenceCreateInfo.calloc(stack); + VkFenceCreateInfo fenceInfo = VUtil.struct( + arena, + VkFenceCreateInfo.SIZEOF, + VkFenceCreateInfo.ALIGNOF, + VkFenceCreateInfo::create + ); fenceInfo.sType(VK_STRUCTURE_TYPE_FENCE_CREATE_INFO); fenceInfo.flags(VK_FENCE_CREATE_SIGNALED_BIT); - LongBuffer pImageAvailableSemaphore = stack.mallocLong(1); - LongBuffer pRenderFinishedSemaphore = stack.mallocLong(1); - LongBuffer pFence = stack.mallocLong(1); + LongBuffer pImageAvailableSemaphore = VUtil.allocateLongBuffer(arena, 1); + LongBuffer pRenderFinishedSemaphore = VUtil.allocateLongBuffer(arena, 1); + LongBuffer pFence = VUtil.allocateLongBuffer(arena, 1); for (int i = 0; i < framesNum; i++) { - if (vkCreateSemaphore(device, semaphoreInfo, null, pImageAvailableSemaphore) != VK_SUCCESS || vkCreateSemaphore(device, semaphoreInfo, null, pRenderFinishedSemaphore) != VK_SUCCESS || vkCreateFence(device, fenceInfo, null, pFence) != VK_SUCCESS) { - throw new RuntimeException("Failed to create synchronization objects for the frame: " + i); } imageAvailableSemaphores.add(pImageAvailableSemaphore.get(0)); renderFinishedSemaphores.add(pRenderFinishedSemaphore.get(0)); inFlightFences.add(pFence.get(0)); - } - } } @@ -203,6 +420,11 @@ public void preInitFrame() { p.round(); p.push("Frame_ops"); + Minecraft minecraft = Minecraft.getInstance(); + float frameTime = minecraft.getDeltaTracker().getGameTimeDeltaPartialTick(false); + float baseTime = minecraft.level != null ? (float) minecraft.level.getGameTime() : 0.0f; + VRenderSystem.setShaderGameTime(baseTime + frameTime); + // runTick might be called recursively, // this check forces sync to avoid upload corruption if (lastReset == currentFrame) { @@ -235,8 +457,7 @@ public void beginFrame() { } - if (skipRendering || recordingCmds) - return; + if (skipRendering || recordingCmds) return; vkWaitForFences(device, inFlightFences.get(currentFrame), true, VUtil.UINT64_MAX); @@ -255,8 +476,7 @@ public void beginFrame() { IntBuffer pImageIndex = stack.mallocInt(1); - int vkResult = vkAcquireNextImageKHR(device, swapChain.getId(), VUtil.UINT64_MAX, - imageAvailableSemaphores.get(currentFrame), VK_NULL_HANDLE, pImageIndex); + int vkResult = vkAcquireNextImageKHR(device, swapChain.getId(), VUtil.UINT64_MAX, imageAvailableSemaphores.get(currentFrame), VK_NULL_HANDLE, pImageIndex); if (vkResult == VK_SUBOPTIMAL_KHR || vkResult == VK_ERROR_OUT_OF_DATE_KHR || swapChainUpdate) { swapChainUpdate = true; @@ -270,37 +490,47 @@ public void beginFrame() { imageIndex = pImageIndex.get(0); - this.beginRenderPass(stack); + this.beginRenderPass(); } p.pop(); } - private void beginRenderPass(MemoryStack stack) { - VkCommandBufferBeginInfo beginInfo = VkCommandBufferBeginInfo.calloc(stack); - beginInfo.sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO); - beginInfo.flags(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); - + private void beginRenderPass() { VkCommandBuffer commandBuffer = currentCmdBuffer; - int vkResult = vkBeginCommandBuffer(commandBuffer, beginInfo); - if (vkResult != VK_SUCCESS) { - throw new RuntimeException("Failed to begin recording command buffer: %s".formatted(VkResult.decode(vkResult))); + try (Arena arena = Arena.ofConfined()) { + VkCommandBufferBeginInfo beginInfo = VUtil.struct( + arena, + VkCommandBufferBeginInfo.SIZEOF, + VkCommandBufferBeginInfo.ALIGNOF, + VkCommandBufferBeginInfo::create + ); + beginInfo.sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO); + beginInfo.flags(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); + + int vkResult = vkBeginCommandBuffer(commandBuffer, beginInfo); + if (vkResult != VK_SUCCESS) { + throw new RuntimeException("Failed to begin recording command buffer: %s".formatted(VkResult.decode(vkResult))); + } } recordingCmds = true; - mainPass.begin(commandBuffer, stack); + mainPass.begin(commandBuffer); resetDynamicState(commandBuffer); } public void endFrame() { - if (skipRendering || !recordingCmds) - return; + if (skipRendering || !recordingCmds) return; Profiler p = Profiler.getMainProfiler(); p.push("End_rendering"); + if (Initializer.CONFIG.enableRayTracing) { + doRayTracing(); + } + mainPass.end(currentCmdBuffer); waitFences(); @@ -313,8 +543,7 @@ public void endFrame() { } private void submitFrame() { - if (swapChainUpdate) - return; + if (swapChainUpdate) return; try (MemoryStack stack = stackPush()) { int vkResult; @@ -362,8 +591,7 @@ private void submitFrame() { * Called in case draw results are needed before the end of the frame */ public void flushCmds() { - if (!this.recordingCmds) - return; + if (!this.recordingCmds) return; try (MemoryStack stack = stackPush()) { int vkResult; @@ -386,9 +614,9 @@ public void flushCmds() { } vkWaitForFences(device, inFlightFences.get(currentFrame), true, VUtil.UINT64_MAX); - - this.beginRenderPass(stack); } + + this.beginRenderPass(); } public void endRenderPass() { @@ -396,13 +624,10 @@ public void endRenderPass() { } public void endRenderPass(VkCommandBuffer commandBuffer) { - if (skipRendering || !recordingCmds || this.boundFramebuffer == null) - return; + if (skipRendering || !recordingCmds || this.boundFramebuffer == null) return; - if (!DYNAMIC_RENDERING) - this.boundRenderPass.endRenderPass(currentCmdBuffer); - else - KHRDynamicRendering.vkCmdEndRenderingKHR(commandBuffer); + if (!DYNAMIC_RENDERING) this.boundRenderPass.endRenderPass(currentCmdBuffer); + else KHRDynamicRendering.vkCmdEndRenderingKHR(commandBuffer); this.boundRenderPass = null; this.boundFramebuffer = null; @@ -411,15 +636,11 @@ public void endRenderPass(VkCommandBuffer commandBuffer) { } public boolean beginRendering(RenderPass renderPass, Framebuffer framebuffer) { - if (skipRendering || !recordingCmds) - return false; + if (skipRendering || !recordingCmds) return false; if (this.boundFramebuffer != framebuffer) { this.endRenderPass(currentCmdBuffer); - - try (MemoryStack stack = stackPush()) { - framebuffer.beginRenderPass(currentCmdBuffer, renderPass, stack); - } + framebuffer.beginRenderPass(currentCmdBuffer, renderPass); this.boundFramebuffer = framebuffer; } @@ -457,10 +678,7 @@ void waitForSwapChain() { // constexpr VkPipelineStageFlags t=VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; try (MemoryStack stack = MemoryStack.stackPush()) { //Empty Submit - VkSubmitInfo info = VkSubmitInfo.calloc(stack) - .sType$Default() - .pWaitSemaphores(stack.longs(imageAvailableSemaphores.get(currentFrame))) - .pWaitDstStageMask(stack.ints(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)); + VkSubmitInfo info = VkSubmitInfo.calloc(stack).sType$Default().pWaitSemaphores(stack.longs(imageAvailableSemaphores.get(currentFrame))).pWaitDstStageMask(stack.ints(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)); vkQueueSubmit(DeviceManager.getGraphicsQueue().queue(), info, inFlightFences.get(currentFrame)); vkWaitForFences(device, inFlightFences.get(currentFrame), true, -1); @@ -545,6 +763,57 @@ public void bindGraphicsPipeline(GraphicsPipeline pipeline) { addUsedPipeline(pipeline); } + public void bindGraphicsPipeline(RenderPipeline pipeline, VertexFormat vertexFormat) { + GraphicsPipeline graphicsPipeline = PipelineManager.getPipeline(pipeline, vertexFormat); + bindGraphicsPipeline(graphicsPipeline); + } + + private void doRayTracing() { + RayTracingPipeline pipeline = PipelineManager.getRayTracingPipeline(); + if (pipeline == null) { + return; + } + bindRayTracingPipeline(pipeline); + + uploadAndBindUBOs(pipeline); + + try (MemoryStack stack = stackPush()) { + VkStridedDeviceAddressRegionKHR raygenShaderSbtEntry = VkStridedDeviceAddressRegionKHR.calloc(stack); + raygenShaderSbtEntry.deviceAddress(pipeline.getSbtBufferAddress()); + raygenShaderSbtEntry.stride(pipeline.getSbtStride()); + raygenShaderSbtEntry.size(pipeline.getSbtStride()); + + VkStridedDeviceAddressRegionKHR missShaderSbtEntry = VkStridedDeviceAddressRegionKHR.calloc(stack); + missShaderSbtEntry.deviceAddress(pipeline.getSbtBufferAddress() + pipeline.getSbtStride()); + missShaderSbtEntry.stride(pipeline.getSbtStride()); + missShaderSbtEntry.size(pipeline.getSbtStride()); + + VkStridedDeviceAddressRegionKHR hitShaderSbtEntry = VkStridedDeviceAddressRegionKHR.calloc(stack); + hitShaderSbtEntry.deviceAddress(pipeline.getSbtBufferAddress() + 2 * pipeline.getSbtStride()); + hitShaderSbtEntry.stride(pipeline.getSbtStride()); + hitShaderSbtEntry.size(pipeline.getSbtStride()); + + VkStridedDeviceAddressRegionKHR callableShaderSbtEntry = VkStridedDeviceAddressRegionKHR.calloc(stack); + + KHRRayTracingPipeline.vkCmdTraceRaysKHR(currentCmdBuffer, raygenShaderSbtEntry, missShaderSbtEntry, hitShaderSbtEntry, callableShaderSbtEntry, swapChain.getWidth(), swapChain.getHeight(), 1); + } + } + + public void bindRayTracingPipeline(RayTracingPipeline pipeline) { + VkCommandBuffer commandBuffer = currentCmdBuffer; + + final long handle = pipeline.getHandle(); + + if (boundPipelineHandle == handle) { + return; + } + + vkCmdBindPipeline(commandBuffer, KHRRayTracingPipeline.VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, handle); + boundPipelineHandle = handle; + boundPipeline = pipeline; + addUsedPipeline(pipeline); + } + public void uploadAndBindUBOs(Pipeline pipeline) { VkCommandBuffer commandBuffer = currentCmdBuffer; pipeline.bindDescriptorSets(commandBuffer, currentFrame); @@ -569,216 +838,31 @@ public Pipeline getBoundPipeline() { return boundPipeline; } - public void setBoundFramebuffer(Framebuffer framebuffer) { - this.boundFramebuffer = framebuffer; - } - public Framebuffer getBoundFramebuffer() { return boundFramebuffer; } - public void setBoundRenderPass(RenderPass boundRenderPass) { - this.boundRenderPass = boundRenderPass; + public void setBoundFramebuffer(Framebuffer framebuffer) { + this.boundFramebuffer = framebuffer; } public RenderPass getBoundRenderPass() { return boundRenderPass; } - public void setMainPass(MainPass mainPass) { - this.mainPass = mainPass; + public void setBoundRenderPass(RenderPass boundRenderPass) { + this.boundRenderPass = boundRenderPass; } public MainPass getMainPass() { return this.mainPass; } - public SwapChain getSwapChain() { - return swapChain; - } - - private static void resetDynamicState(VkCommandBuffer commandBuffer) { - vkCmdSetDepthBias(commandBuffer, 0.0F, 0.0F, 0.0F); - - vkCmdSetLineWidth(commandBuffer, 1.0F); - } - - public static void setDepthBias(float constant, float slope) { - VkCommandBuffer commandBuffer = INSTANCE.currentCmdBuffer; - - vkCmdSetDepthBias(commandBuffer, constant, 0.0f, slope); - } - - public static void clearAttachments(int v) { - Framebuffer framebuffer = Renderer.getInstance().boundFramebuffer; - if (framebuffer == null) - return; - - clearAttachments(v, framebuffer.getWidth(), framebuffer.getHeight()); - } - - public static void clearAttachments(int v, int width, int height) { - if (skipRendering) - return; - - try (MemoryStack stack = stackPush()) { - //ClearValues have to be different for each attachment to clear, - //it seems it uses the same buffer: color and depth values override themselves - VkClearValue colorValue = VkClearValue.calloc(stack); - colorValue.color().float32(VRenderSystem.clearColor); - - VkClearValue depthValue = VkClearValue.calloc(stack); - depthValue.depthStencil().set(VRenderSystem.clearDepthValue, 0); //Use fast depth clears if possible - - int attachmentsCount = v == (GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT) ? 2 : 1; - final VkClearAttachment.Buffer pAttachments = VkClearAttachment.malloc(attachmentsCount, stack); - switch (v) { - case GL_DEPTH_BUFFER_BIT -> { - - VkClearAttachment clearDepth = pAttachments.get(0); - clearDepth.aspectMask(VK_IMAGE_ASPECT_DEPTH_BIT); - clearDepth.colorAttachment(0); - clearDepth.clearValue(depthValue); - } - case GL_COLOR_BUFFER_BIT -> { - - VkClearAttachment clearColor = pAttachments.get(0); - clearColor.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT); - clearColor.colorAttachment(0); - clearColor.clearValue(colorValue); - } - case GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT -> { - - VkClearAttachment clearColor = pAttachments.get(0); - clearColor.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT); - clearColor.colorAttachment(0); - clearColor.clearValue(colorValue); - - VkClearAttachment clearDepth = pAttachments.get(1); - clearDepth.aspectMask(VK_IMAGE_ASPECT_DEPTH_BIT); - clearDepth.colorAttachment(0); - clearDepth.clearValue(depthValue); - } - default -> throw new RuntimeException("unexpected value"); - } - - //Rect to clear - VkRect2D renderArea = VkRect2D.malloc(stack); - renderArea.offset().set(0, 0); - renderArea.extent().set(width, height); - - VkClearRect.Buffer pRect = VkClearRect.malloc(1, stack); - pRect.rect(renderArea); - pRect.baseArrayLayer(0); - pRect.layerCount(1); - - vkCmdClearAttachments(INSTANCE.currentCmdBuffer, pAttachments, pRect); - } - } - - public static void setInvertedViewport(int x, int y, int width, int height) { - setViewportState(x, y + height, width, -height); - } - - public static void resetViewport() { - int width = INSTANCE.getSwapChain().getWidth(); - int height = INSTANCE.getSwapChain().getHeight(); - - setViewportState(0, 0, width, height); - } - - public static void setViewportState(int x, int y, int width, int height) { - GlStateManager._viewport(x, y, width, height); - } - - public static void setViewport(int x, int y, int width, int height) { - try (MemoryStack stack = stackPush()) { - setViewport(x, y, width, height, stack); - } - } - - public static void setViewport(int x, int y, int width, int height, MemoryStack stack) { - if (!INSTANCE.recordingCmds) - return; - - VkViewport.Buffer viewport = VkViewport.malloc(1, stack); - viewport.x(x); - viewport.y(height + y); - viewport.width(width); - viewport.height(-height); - viewport.minDepth(0.0f); - viewport.maxDepth(1.0f); - - vkCmdSetViewport(INSTANCE.currentCmdBuffer, 0, viewport); - } - - public static void setScissor(int x, int y, int width, int height) { - if (INSTANCE.boundFramebuffer == null) - return; - - try (MemoryStack stack = stackPush()) { - int framebufferHeight = INSTANCE.boundFramebuffer.getHeight(); - - x = Math.max(0, x); - - VkRect2D.Buffer scissor = VkRect2D.malloc(1, stack); - scissor.offset().set(x, framebufferHeight - (y + height)); - scissor.extent().set(width, height); - - vkCmdSetScissor(INSTANCE.currentCmdBuffer, 0, scissor); - } - } - - public static void resetScissor() { - if (INSTANCE.boundFramebuffer == null) - return; - - try (MemoryStack stack = stackPush()) { - VkRect2D.Buffer scissor = INSTANCE.boundFramebuffer.scissor(stack); - vkCmdSetScissor(INSTANCE.currentCmdBuffer, 0, scissor); - } - } - - public static void pushDebugSection(String s) { - if (Vulkan.ENABLE_VALIDATION_LAYERS) { - VkCommandBuffer commandBuffer = INSTANCE.currentCmdBuffer; - - try (MemoryStack stack = stackPush()) { - VkDebugUtilsLabelEXT markerInfo = VkDebugUtilsLabelEXT.calloc(stack); - markerInfo.sType(VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT); - ByteBuffer string = stack.UTF8(s); - markerInfo.pLabelName(string); - vkCmdBeginDebugUtilsLabelEXT(commandBuffer, markerInfo); - } - } - } - - public static void popDebugSection() { - if (Vulkan.ENABLE_VALIDATION_LAYERS) { - VkCommandBuffer commandBuffer = INSTANCE.currentCmdBuffer; - - vkCmdEndDebugUtilsLabelEXT(commandBuffer); - } - } - - public static void popPushDebugSection(String s) { - popDebugSection(); - pushDebugSection(s); - } - - public static int getFramesNum() { - return INSTANCE.framesNum; - } - - public static VkCommandBuffer getCommandBuffer() { - return INSTANCE.currentCmdBuffer; - } - - public static boolean isRecording() { - return INSTANCE.recordingCmds; + public void setMainPass(MainPass mainPass) { + this.mainPass = mainPass; } - public static void scheduleSwapChainUpdate() { - swapChainUpdate = true; + public SwapChain getSwapChain() { + return swapChain; } } diff --git a/src/main/java/net/vulkanmod/vulkan/Synchronization.java b/src/main/java/net/vulkanmod/vulkan/Synchronization.java index 609052db3..ee508a230 100644 --- a/src/main/java/net/vulkanmod/vulkan/Synchronization.java +++ b/src/main/java/net/vulkanmod/vulkan/Synchronization.java @@ -24,22 +24,31 @@ public class Synchronization { this.fences = MemoryUtil.memAllocLong(allocSize); } + public static void waitFence(long fence) { + VkDevice device = Vulkan.getVkDevice(); + + vkWaitForFences(device, fence, true, VUtil.UINT64_MAX); + } + + public static boolean checkFenceStatus(long fence) { + VkDevice device = Vulkan.getVkDevice(); + return vkGetFenceStatus(device, fence) == VK_SUCCESS; + } + public synchronized void addCommandBuffer(CommandPool.CommandBuffer commandBuffer) { this.addFence(commandBuffer.getFence()); this.commandBuffers.add(commandBuffer); } public synchronized void addFence(long fence) { - if (idx == ALLOCATION_SIZE) - waitFences(); + if (idx == ALLOCATION_SIZE) waitFences(); fences.put(idx, fence); idx++; } public synchronized void waitFences() { - if (idx == 0) - return; + if (idx == 0) return; VkDevice device = Vulkan.getVkDevice(); @@ -54,15 +63,4 @@ public synchronized void waitFences() { idx = 0; } - public static void waitFence(long fence) { - VkDevice device = Vulkan.getVkDevice(); - - vkWaitForFences(device, fence, true, VUtil.UINT64_MAX); - } - - public static boolean checkFenceStatus(long fence) { - VkDevice device = Vulkan.getVkDevice(); - return vkGetFenceStatus(device, fence) == VK_SUCCESS; - } - } diff --git a/src/main/java/net/vulkanmod/vulkan/SystemInfo.java b/src/main/java/net/vulkanmod/vulkan/SystemInfo.java index d64417c40..3c0d664cf 100644 --- a/src/main/java/net/vulkanmod/vulkan/SystemInfo.java +++ b/src/main/java/net/vulkanmod/vulkan/SystemInfo.java @@ -9,4 +9,4 @@ public class SystemInfo { CentralProcessor centralProcessor = new oshi.SystemInfo().getHardware().getProcessor(); cpuInfo = String.format("%s", centralProcessor.getProcessorIdentifier().getName()).replaceAll("\\s+", " "); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java index db4996d69..3b63db968 100644 --- a/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java +++ b/src/main/java/net/vulkanmod/vulkan/VRenderSystem.java @@ -1,7 +1,6 @@ package net.vulkanmod.vulkan; import com.mojang.blaze3d.platform.Window; - import net.minecraft.client.Minecraft; import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.shader.PipelineState; @@ -12,49 +11,44 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.system.MemoryUtil; -import static org.lwjgl.vulkan.VK10.*; - import java.nio.ByteBuffer; import java.nio.FloatBuffer; +import static org.lwjgl.vulkan.VK10.*; + public abstract class VRenderSystem { private static final float DEFAULT_DEPTH_VALUE = 1.0f; - - private static long window; - + private static final float[] shaderColorArray = new float[]{1.0f, 1.0f, 1.0f, 1.0f}; + private static final float[] shaderFogColorArray = new float[]{0.0f, 0.0f, 0.0f, 1.0f}; public static boolean depthTest = true; public static boolean depthMask = true; public static int depthFun = 515; public static int topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; public static int polygonMode = VK_POLYGON_MODE_FILL; public static boolean canSetLineWidth = false; - public static int colorMask = PipelineState.ColorMask.getColorMask(true, true, true, true); - public static boolean cull = true; - public static boolean logicOp = false; public static int logicOpFun = 0; - public static float clearDepthValue = DEFAULT_DEPTH_VALUE; public static FloatBuffer clearColor = MemoryUtil.memCallocFloat(4); - public static MappedBuffer modelViewMatrix = new MappedBuffer(16 * 4); public static MappedBuffer projectionMatrix = new MappedBuffer(16 * 4); public static MappedBuffer TextureMatrix = new MappedBuffer(16 * 4); public static MappedBuffer MVP = new MappedBuffer(16 * 4); - public static MappedBuffer modelOffset = new MappedBuffer(3 * 4); public static MappedBuffer lightDirection0 = new MappedBuffer(3 * 4); public static MappedBuffer lightDirection1 = new MappedBuffer(3 * 4); - public static MappedBuffer shaderColor = new MappedBuffer(4 * 4); public static MappedBuffer shaderFogColor = new MappedBuffer(4 * 4); - public static MappedBuffer screenSize = new MappedBuffer(2 * 4); - public static float alphaCutout = 0.0f; - + private static long window; + private static float fogRenderStart; + private static float fogRenderEnd; + private static int fogShapeIndex; + private static float shaderGameTime; + private static float glintAlpha = 1.0f; private static boolean depthBiasEnabled = false; private static float depthBiasConstant = 0.0f; private static float depthBiasSlope = 0.0f; @@ -108,14 +102,14 @@ public static void calculateMVP() { P.mul(MV).get(MVP.buffer); } - public static void setTextureMatrix(Matrix4f mat) { - mat.get(TextureMatrix.buffer.asFloatBuffer()); - } - public static MappedBuffer getTextureMatrix() { return TextureMatrix; } + public static void setTextureMatrix(Matrix4f mat) { + mat.get(TextureMatrix.buffer.asFloatBuffer()); + } + public static MappedBuffer getModelViewMatrix() { return modelViewMatrix; } @@ -130,17 +124,80 @@ public static MappedBuffer getMVP() { public static void setModelOffset(float x, float y, float z) { long ptr = modelOffset.ptr; - VUtil.UNSAFE.putFloat(ptr, x); - VUtil.UNSAFE.putFloat(ptr + 4, y); - VUtil.UNSAFE.putFloat(ptr + 8, z); + VUtil.putFloat(ptr, x); + VUtil.putFloat(ptr + 4, y); + VUtil.putFloat(ptr + 8, z); } public static void setShaderColor(float f1, float f2, float f3, float f4) { ColorUtil.setRGBA_Buffer(shaderColor, f1, f2, f3, f4); + shaderColorArray[0] = f1; + shaderColorArray[1] = f2; + shaderColorArray[2] = f3; + shaderColorArray[3] = f4; } public static void setShaderFogColor(float f1, float f2, float f3, float f4) { ColorUtil.setRGBA_Buffer(shaderFogColor, f1, f2, f3, f4); + shaderFogColorArray[0] = f1; + shaderFogColorArray[1] = f2; + shaderFogColorArray[2] = f3; + shaderFogColorArray[3] = f4; + } + + public static void setShaderLights(float lx0, float ly0, float lz0, float lx1, float ly1, float lz1) { + lightDirection0.buffer.putFloat(0, lx0); + lightDirection0.buffer.putFloat(4, ly0); + lightDirection0.buffer.putFloat(8, lz0); + + lightDirection1.buffer.putFloat(0, lx1); + lightDirection1.buffer.putFloat(4, ly1); + lightDirection1.buffer.putFloat(8, lz1); + } + + public static void setFogParameters(float environmentalStart, float renderStart, float environmentalEnd, float renderEnd, float skyEnd, float cloudEnd) { + fogRenderStart = renderStart; + fogRenderEnd = renderEnd; + } + + public static float[] getShaderColorArray() { + return shaderColorArray; + } + + public static float[] getShaderFogColorArray() { + return shaderFogColorArray; + } + + public static float getFogStart() { + return fogRenderStart; + } + + public static float getFogEnd() { + return fogRenderEnd; + } + + public static int getFogShapeIndex() { + return fogShapeIndex; + } + + public static void setFogShapeIndex(int shapeIndex) { + fogShapeIndex = shapeIndex; + } + + public static float getShaderGameTime() { + return shaderGameTime; + } + + public static void setShaderGameTime(float gameTime) { + shaderGameTime = gameTime; + } + + public static float getGlintAlpha() { + return glintAlpha; + } + + public static void setGlintAlpha(float alpha) { + glintAlpha = alpha; } public static MappedBuffer getShaderColor() { @@ -175,7 +232,7 @@ public static void depthMask(boolean b) { public static void setPrimitiveTopologyGL(final int mode) { VRenderSystem.topology = switch (mode) { - case GL11.GL_LINES, GL11.GL_LINE_STRIP -> VK_PRIMITIVE_TOPOLOGY_LINE_LIST; + case GL11.GL_LINES, GL11.GL_LINE_STRIP -> VK_PRIMITIVE_TOPOLOGY_LINE_LIST; case GL11.GL_TRIANGLE_FAN, GL11.GL_TRIANGLES, GL11.GL_TRIANGLE_STRIP -> VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; default -> throw new RuntimeException(String.format("Unknown GL primitive topology: %s", mode)); }; diff --git a/src/main/java/net/vulkanmod/vulkan/Vulkan.java b/src/main/java/net/vulkanmod/vulkan/Vulkan.java index 0ab7e7124..dad541306 100644 --- a/src/main/java/net/vulkanmod/vulkan/Vulkan.java +++ b/src/main/java/net/vulkanmod/vulkan/Vulkan.java @@ -3,9 +3,9 @@ import net.vulkanmod.vulkan.device.Device; import net.vulkanmod.vulkan.device.DeviceManager; import net.vulkanmod.vulkan.framebuffer.SwapChain; -import net.vulkanmod.vulkan.memory.buffer.Buffer; import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.memory.MemoryTypes; +import net.vulkanmod.vulkan.memory.buffer.Buffer; import net.vulkanmod.vulkan.memory.buffer.StagingBuffer; import net.vulkanmod.vulkan.queue.Queue; import net.vulkanmod.vulkan.shader.Pipeline; @@ -31,7 +31,11 @@ import static org.lwjgl.util.vma.Vma.vmaCreateAllocator; import static org.lwjgl.util.vma.Vma.vmaDestroyAllocator; import static org.lwjgl.vulkan.EXTDebugUtils.*; +import static org.lwjgl.vulkan.KHRAccelerationStructure.VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME; +import static org.lwjgl.vulkan.KHRBufferDeviceAddress.VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME; +import static org.lwjgl.vulkan.KHRDeferredHostOperations.VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME; import static org.lwjgl.vulkan.KHRDynamicRendering.VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME; +import static org.lwjgl.vulkan.KHRRayTracingPipeline.VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME; import static org.lwjgl.vulkan.KHRSwapchain.VK_KHR_SWAPCHAIN_EXTENSION_NAME; import static org.lwjgl.vulkan.VK10.*; import static org.lwjgl.vulkan.VK12.VK_API_VERSION_1_2; @@ -45,6 +49,18 @@ public class Vulkan { public static final boolean DYNAMIC_RENDERING = false; public static final Set VALIDATION_LAYERS; + public static final Set REQUIRED_EXTENSION = getRequiredExtensionSet(); + public static long window; + public static boolean use24BitsDepthFormat = true; + private static VkInstance instance; + private static long debugMessenger; + private static long surface; + private static long commandPool; + private static VkCommandBuffer immediateCmdBuffer; + private static long immediateFence; + private static long allocator; + private static StagingBuffer[] stagingBuffers; + private static int DEFAULT_DEPTH_FORMAT = 0; static { if (ENABLE_VALIDATION_LAYERS) { @@ -58,10 +74,8 @@ public class Vulkan { } } - public static final Set REQUIRED_EXTENSION = getRequiredExtensionSet(); - private static Set getRequiredExtensionSet() { - ArrayList extensions = new ArrayList<>(List.of(VK_KHR_SWAPCHAIN_EXTENSION_NAME)); + ArrayList extensions = new ArrayList<>(List.of(VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME, VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME, VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME, VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME)); if (DYNAMIC_RENDERING) { extensions.add(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME); @@ -86,14 +100,12 @@ private static int debugCallback(int messageSeverity, int messageType, long pCal System.err.println(s); - if ((messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0) - System.nanoTime(); + if ((messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0) System.nanoTime(); return VK_FALSE; } - private static int createDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerCreateInfoEXT createInfo, - VkAllocationCallbacks allocationCallbacks, LongBuffer pDebugMessenger) { + private static int createDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerCreateInfoEXT createInfo, VkAllocationCallbacks allocationCallbacks, LongBuffer pDebugMessenger) { if (vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT") != NULL) { return vkCreateDebugUtilsMessengerEXT(instance, createInfo, allocationCallbacks, pDebugMessenger); @@ -118,23 +130,6 @@ public static long getAllocator() { return allocator; } - public static long window; - - private static VkInstance instance; - private static long debugMessenger; - private static long surface; - - private static long commandPool; - private static VkCommandBuffer immediateCmdBuffer; - private static long immediateFence; - - private static long allocator; - - private static StagingBuffer[] stagingBuffers; - - public static boolean use24BitsDepthFormat = true; - private static int DEFAULT_DEPTH_FORMAT = 0; - public static void initVulkan(long window) { createInstance(); setupDebugMessenger(); @@ -195,6 +190,7 @@ public static void cleanUp() { destroyDebugUtilsMessengerEXT(instance, debugMessenger, null); KHRSurface.vkDestroySurfaceKHR(instance, surface, null); vkDestroyInstance(instance, null); + } private static void freeStagingBuffers() { @@ -214,9 +210,9 @@ private static void createInstance() { VkApplicationInfo appInfo = VkApplicationInfo.calloc(stack); appInfo.sType(VK_STRUCTURE_TYPE_APPLICATION_INFO); - appInfo.pApplicationName(stack.UTF8Safe("VulkanMod")); + appInfo.pApplicationName(Objects.requireNonNull(stack.UTF8Safe("VulkanMod"))); appInfo.applicationVersion(VK_MAKE_VERSION(1, 0, 0)); - appInfo.pEngineName(stack.UTF8Safe("VulkanMod Engine")); + appInfo.pEngineName(Objects.requireNonNull(stack.UTF8Safe("VulkanMod Engine"))); appInfo.engineVersion(VK_MAKE_VERSION(1, 0, 0)); appInfo.apiVersion(VK_API_VERSION_1_2); @@ -241,7 +237,14 @@ private static void createInstance() { int result = vkCreateInstance(createInfo, null, instancePtr); checkResult(result, "Failed to create instance"); - instance = new VkInstance(instancePtr.get(0), createInfo); + // Workaround for LWJGL 3.3.x + Java 25 infinite recursion bug in VkInstance constructor + // The standard constructor with createInfo: new VkInstance(handle, createInfo) + // causes stack overflow in getInstanceCapabilities() -> getAvailableDeviceExtensions() + // + // Workaround: Pass null for createInfo to skip automatic capability detection + // Capabilities will need to be manually queried later if needed + long handle = instancePtr.get(0); + instance = new VkInstance(handle, null); } } @@ -257,9 +260,7 @@ static boolean checkValidationLayerSupport() { vkEnumerateInstanceLayerProperties(layerCount, availableLayers); - Set availableLayerNames = availableLayers.stream() - .map(VkLayerProperties::layerNameString) - .collect(toSet()); + Set availableLayerNames = availableLayers.stream().map(VkLayerProperties::layerNameString).collect(toSet()); return availableLayerNames.containsAll(Vulkan.VALIDATION_LAYERS); } @@ -288,8 +289,7 @@ private static void setupDebugMessenger() { LongBuffer pDebugMessenger = stack.longs(VK_NULL_HANDLE); - checkResult(createDebugUtilsMessengerEXT(instance, createInfo, null, pDebugMessenger), - "Failed to set up debug messenger"); + checkResult(createDebugUtilsMessengerEXT(instance, createInfo, null, pDebugMessenger), "Failed to set up debug messenger"); debugMessenger = pDebugMessenger.get(0); } @@ -313,8 +313,7 @@ private static void createSurface(long handle) { LongBuffer pSurface = stack.longs(VK_NULL_HANDLE); - checkResult(glfwCreateWindowSurface(instance, window, null, pSurface), - "Failed to create window surface"); + checkResult(glfwCreateWindowSurface(instance, window, null, pSurface), "Failed to create window surface"); surface = pSurface.get(0); } @@ -335,8 +334,7 @@ private static void createVma() { PointerBuffer pAllocator = stack.pointers(VK_NULL_HANDLE); - checkResult(vmaCreateAllocator(allocatorCreateInfo, pAllocator), - "Failed to create Allocator"); + checkResult(vmaCreateAllocator(allocatorCreateInfo, pAllocator), "Failed to create Allocator"); allocator = pAllocator.get(0); } @@ -355,8 +353,7 @@ private static void createCommandPool() { LongBuffer pCommandPool = stack.mallocLong(1); - checkResult(vkCreateCommandPool(DeviceManager.vkDevice, poolInfo, null, pCommandPool), - "Failed to create command pool"); + checkResult(vkCreateCommandPool(DeviceManager.vkDevice, poolInfo, null, pCommandPool), "Failed to create command pool"); commandPool = pCommandPool.get(0); } @@ -416,4 +413,3 @@ public static Device getDevice() { return DeviceManager.device; } } - diff --git a/src/main/java/net/vulkanmod/vulkan/blaze/VulkanCommandEncoder.java b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanCommandEncoder.java new file mode 100644 index 000000000..a7c1a14f6 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanCommandEncoder.java @@ -0,0 +1,231 @@ +package net.vulkanmod.vulkan.blaze; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.buffers.GpuBufferSlice; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.systems.CommandEncoder; +import com.mojang.blaze3d.systems.RenderPass; +import com.mojang.blaze3d.textures.GpuTexture; +import com.mojang.blaze3d.textures.GpuTextureView; +import com.mojang.blaze3d.vertex.VertexFormat; +import java.lang.foreign.MemorySegment; +import java.util.Collection; +import java.util.OptionalDouble; +import java.util.OptionalInt; +import java.util.function.Supplier; + +/** + * Placeholder implementation. Methods currently throw + * {@link UnsupportedOperationException} until the Vulkan translation layer + * is implemented. + */ +public final class VulkanCommandEncoder implements CommandEncoder { + + private final VulkanGpuDevice device; + private VulkanRenderPass currentPass; + private boolean inRenderPass = false; + + VulkanCommandEncoder(VulkanGpuDevice device) { + this.device = device; + } + + public VulkanGpuDevice device() { + return device; + } + + private static UnsupportedOperationException nyi(String method) { + return new UnsupportedOperationException("CommandEncoder#" + method + " is not implemented yet"); + } + + private static VulkanGpuBuffer expectBuffer(GpuBuffer buffer) { + if (buffer instanceof VulkanGpuBuffer vulkanBuffer) { + return vulkanBuffer; + } + throw new IllegalArgumentException("Unsupported buffer implementation: " + buffer.getClass().getName()); + } + + private static VulkanGpuTexture expectTexture(GpuTexture texture) { + if (texture instanceof VulkanGpuTexture vkTexture) { + return vkTexture; + } + throw new IllegalArgumentException("Unsupported texture implementation: " + texture.getClass().getName()); + } + + @Override + public RenderPass createRenderPass(Supplier label, + GpuTextureView colorTarget, + OptionalInt colorLevel) { + return createRenderPass(label, colorTarget, colorLevel, null, OptionalDouble.empty()); + } + + @Override + public RenderPass createRenderPass(Supplier label, + GpuTextureView colorTarget, + OptionalInt colorLevel, + GpuTextureView depthTarget, + OptionalDouble clearDepth) { + VulkanGpuTexture color = expectTexture(colorTarget.texture()); + VulkanGpuTexture depth = depthTarget != null ? expectTexture(depthTarget.texture()) : null; + if (inRenderPass) { + throw new IllegalStateException("Close the existing render pass before creating a new one!"); + } + VulkanFramebuffer framebuffer = new VulkanFramebuffer(color, depth); + VulkanRenderPassState state = VulkanRenderPassState.create(framebuffer, + colorTarget, colorLevel, depthTarget, clearDepth); + currentPass = new VulkanRenderPass(this, state); + inRenderPass = true; + return currentPass; + } + + void onRenderPassClosed() { + inRenderPass = false; + currentPass = null; + } + + @Override + public void clearColorTexture(GpuTexture texture, int level) { + throw nyi("clearColorTexture"); + } + + @Override + public void clearColorAndDepthTextures(GpuTexture color, + int level, + GpuTexture depth, + double depthValue) { + throw nyi("clearColorAndDepthTextures"); + } + + @Override + public void clearColorAndDepthTextures(GpuTexture color, + int level, + GpuTexture depth, + double depthValue, + int x, + int y, + int width, + int height) { + throw nyi("clearColorAndDepthTextures"); + } + + @Override + public void clearDepthTexture(GpuTexture texture, double value) { + throw nyi("clearDepthTexture"); + } + + @Override + public void writeToBuffer(GpuBufferSlice slice, java.nio.ByteBuffer data) { + VulkanGpuBuffer buffer = expectBuffer(slice.buffer()); + int available = Math.min(data.remaining(), slice.length()); + if (available <= 0) { + return; + } + MemorySegment src = MemorySegment.ofBuffer(data).asSlice(data.position(), available); + MemorySegment dst = buffer.mapSegment(slice.offset(), available); + dst.copyFrom(src); + data.position(data.position() + available); + } + + @Override + public GpuBuffer.MappedView mapBuffer(GpuBuffer buffer, boolean read, boolean write) { + VulkanGpuBuffer vkBuffer = expectBuffer(buffer); + MemorySegment segment = vkBuffer.mapSegment(0, buffer.size()); + return new VulkanGpuBuffer.VulkanMappedView(segment); + } + + @Override + public GpuBuffer.MappedView mapBuffer(GpuBufferSlice slice, boolean read, boolean write) { + VulkanGpuBuffer vkBuffer = expectBuffer(slice.buffer()); + MemorySegment segment = vkBuffer.mapSegment(slice.offset(), slice.length()); + return new VulkanGpuBuffer.VulkanMappedView(segment); + } + + @Override + public void copyToBuffer(GpuBufferSlice src, GpuBufferSlice dst) { + VulkanGpuBuffer srcBuffer = expectBuffer(src.buffer()); + VulkanGpuBuffer dstBuffer = expectBuffer(dst.buffer()); + int length = Math.min(src.length(), dst.length()); + if (length <= 0) { + return; + } + MemorySegment srcSegment = srcBuffer.mapSegment(src.offset(), length); + MemorySegment dstSegment = dstBuffer.mapSegment(dst.offset(), length); + dstSegment.copyFrom(srcSegment); + } + + @Override + public void writeToTexture(GpuTexture texture, NativeImage image) { + throw nyi("writeToTexture"); + } + + @Override + public void writeToTexture(GpuTexture texture, + NativeImage image, + int x, + int y, + int width, + int height, + int level, + int depth, + int layer, + int stride) { + throw nyi("writeToTexture"); + } + + @Override + public void writeToTexture(GpuTexture texture, + java.nio.ByteBuffer data, + NativeImage.Format format, + int x, + int y, + int width, + int height, + int level, + int depth) { + throw nyi("writeToTexture"); + } + + @Override + public void copyTextureToBuffer(GpuTexture texture, + GpuBuffer buffer, + int level, + Runnable onComplete, + int stride) { + throw nyi("copyTextureToBuffer"); + } + + @Override + public void copyTextureToBuffer(GpuTexture texture, + GpuBuffer buffer, + int level, + Runnable onComplete, + int x, + int y, + int width, + int height, + int stride) { + throw nyi("copyTextureToBuffer"); + } + + @Override + public void copyTextureToTexture(GpuTexture src, + GpuTexture dst, + int srcLevel, + int dstLevel, + int srcX, + int srcY, + int width, + int height, + int depth) { + throw nyi("copyTextureToTexture"); + } + + @Override + public void presentTexture(GpuTextureView view) { + throw nyi("presentTexture"); + } + + @Override + public VulkanGpuFence createFence() { + return new VulkanGpuFence(); + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/blaze/VulkanFramebuffer.java b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanFramebuffer.java new file mode 100644 index 000000000..2db6bb6a6 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanFramebuffer.java @@ -0,0 +1,33 @@ +package net.vulkanmod.vulkan.blaze; + +import net.vulkanmod.vulkan.framebuffer.Framebuffer; +import net.vulkanmod.vulkan.texture.VulkanImage; + +/** + * Thin wrapper around the existing {@link Framebuffer} class so the Vulkan + * render pass placeholder can store colour/depth attachments without touching + * Mojang's GL objects. + */ +final class VulkanFramebuffer { + + private final Framebuffer framebuffer; + + VulkanFramebuffer(VulkanGpuTexture color, VulkanGpuTexture depth) { + VulkanImage colorImage = color != null ? color.image() : null; + VulkanImage depthImage = depth != null ? depth.image() : null; + this.framebuffer = Framebuffer.builder(colorImage, depthImage) + .build(); + } + + Framebuffer handle() { + return framebuffer; + } + + VulkanImage colorAttachment() { + return framebuffer.getColorAttachment(); + } + + VulkanImage depthAttachment() { + return framebuffer.getDepthAttachment(); + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuBuffer.java b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuBuffer.java new file mode 100644 index 000000000..28e0532be --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuBuffer.java @@ -0,0 +1,91 @@ +package net.vulkanmod.vulkan.blaze; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import net.vulkanmod.vulkan.memory.MemoryTypes; +import net.vulkanmod.vulkan.memory.buffer.Buffer; +import java.lang.foreign.MemorySegment; +import java.nio.ByteBuffer; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Minimal Vulkan-backed buffer wrapper. Actual upload and command submission + * will be implemented during later stages of the refactor. + */ +public final class VulkanGpuBuffer extends GpuBuffer { + + private final VulkanGpuDevice device; + private final String label; + private final Buffer backingBuffer; + private final AtomicBoolean closed = new AtomicBoolean(false); + + VulkanGpuBuffer(VulkanGpuDevice device, String label, int usage, int size) { + super(usage, size); + this.device = device; + this.label = label; + this.backingBuffer = new Buffer(usage, MemoryTypes.HOST_MEM); + this.backingBuffer.createBuffer(size); + } + + public VulkanGpuDevice device() { + return device; + } + + public Buffer backingBuffer() { + return backingBuffer; + } + + public String label() { + return label; + } + + void upload(ByteBuffer data) { + backingBuffer.copyBuffer(data, data.remaining()); + } + + @Override + public boolean isClosed() { + return closed.get(); + } + + @Override + public void close() { + if (closed.compareAndSet(false, true)) { + backingBuffer.scheduleFree(); + } + } + + @Override + public com.mojang.blaze3d.buffers.GpuBufferSlice slice(int offset, int length) { + return new com.mojang.blaze3d.buffers.GpuBufferSlice(this, offset, length); + } + + @Override + public com.mojang.blaze3d.buffers.GpuBufferSlice slice() { + return new com.mojang.blaze3d.buffers.GpuBufferSlice(this, 0, (int) backingBuffer.getBufferSize()); + } + + MemorySegment mapSegment(int offset, int length) { + long base = backingBuffer.getDataPtr() + offset; + return MemorySegment.ofAddress(base).reinterpret(length); + } + + static final class VulkanMappedView implements GpuBuffer.MappedView { + private final MemorySegment segment; + private final ByteBuffer view; + + VulkanMappedView(MemorySegment segment) { + this.segment = segment; + this.view = segment.asByteBuffer(); + } + + @Override + public ByteBuffer data() { + return view; + } + + @Override + public void close() { + // Host coherent memory, nothing to flush for now. + } + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuDevice.java b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuDevice.java new file mode 100644 index 000000000..172bd594f --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuDevice.java @@ -0,0 +1,264 @@ +package net.vulkanmod.vulkan.blaze; + +import com.mojang.blaze3d.pipeline.CompiledRenderPipeline; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.shaders.ShaderType; +import com.mojang.blaze3d.systems.CommandEncoder; +import com.mojang.blaze3d.systems.GpuDevice; +import com.mojang.blaze3d.textures.GpuTexture; +import com.mojang.blaze3d.textures.GpuTextureView; +import com.mojang.blaze3d.textures.TextureFormat; +import net.minecraft.resources.ResourceLocation; +import net.vulkanmod.vulkan.Renderer; +import net.vulkanmod.vulkan.device.DeviceManager; +import net.vulkanmod.vulkan.texture.VulkanImage; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.function.BiFunction; + +import static org.lwjgl.vulkan.VK10.VK_FORMAT_D32_SFLOAT; +import static org.lwjgl.vulkan.VK10.VK_FORMAT_R8_SINT; +import static org.lwjgl.vulkan.VK10.VK_FORMAT_R8_UNORM; +import static org.lwjgl.vulkan.VK10.VK_FORMAT_R8G8B8A8_UNORM; +import static org.lwjgl.vulkan.VK10.VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; +import static org.lwjgl.vulkan.VK10.VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; +import static org.lwjgl.vulkan.VK10.VK_IMAGE_USAGE_SAMPLED_BIT; +import static org.lwjgl.vulkan.VK10.VK_IMAGE_USAGE_TRANSFER_DST_BIT; +import static org.lwjgl.vulkan.VK10.VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + +/** + * WIP Vulkan-backed replacement for Mojang's {@link com.mojang.blaze3d.opengl.GlDevice}. + * At this stage the implementation only satisfies the type contracts so we can + * wire it into RenderSystem; concrete behaviour will be filled in incrementally. + */ +public final class VulkanGpuDevice implements GpuDevice { + + private final long windowHandle; + private final int debugVerbosity; + private final boolean debugSync; + private final boolean debugLabels; + private final BiFunction shaderSourceProvider; + + public VulkanGpuDevice(long windowHandle, + int debugVerbosity, + boolean debugSync, + BiFunction shaderSourceProvider, + boolean debugLabels) { + this.windowHandle = windowHandle; + this.debugVerbosity = debugVerbosity; + this.debugSync = debugSync; + this.shaderSourceProvider = shaderSourceProvider; + this.debugLabels = debugLabels; + + // Ensure Vulkan runtime is initialised. Renderer boot happens elsewhere, + // but we force creation of the singleton so later calls don't explode. + Renderer.getInstance(); + } + + public long getWindowHandle() { + return windowHandle; + } + + public boolean isDebugSyncEnabled() { + return debugSync; + } + + public boolean isDebugLabelsEnabled() { + return debugLabels; + } + + public BiFunction shaderSourceProvider() { + return shaderSourceProvider; + } + + @Override + public CommandEncoder createCommandEncoder() { + return new VulkanCommandEncoder(this); + } + + @Override + public GpuTexture createTexture(java.util.function.Supplier label, + int usage, + TextureFormat format, + int width, + int height, + int depthOrLayers, + int mipLevels) { + String name = label != null ? label.get() : "unnamed"; + return createTextureInternal(name, usage, format, width, height, depthOrLayers, mipLevels); + } + + @Override + public GpuTexture createTexture(String label, + int usage, + TextureFormat format, + int width, + int height, + int depthOrLayers, + int mipLevels) { + String name = Objects.requireNonNullElse(label, "unnamed"); + return createTextureInternal(name, usage, format, width, height, depthOrLayers, mipLevels); + } + + private VulkanGpuTexture createTextureInternal(String label, + int usage, + TextureFormat format, + int width, + int height, + int depthOrLayers, + int mipLevels) { + if (depthOrLayers > 1) { + throw new UnsupportedOperationException("Array/3D textures are not implemented yet"); + } + + VulkanGpuTexture texture = new VulkanGpuTexture(this, usage, label, format, width, height, depthOrLayers, mipLevels); + + int vkFormat = mapFormat(format); + int vkUsage = resolveUsage(usage, format); + + VulkanImage image = VulkanImage.builder(width, height) + .setName(label) + .setFormat(vkFormat) + .setMipLevels(mipLevels) + .setUsage(vkUsage) + .createVulkanImage(); + + texture.attachImage(image); + texture.setUseMipmaps(mipLevels > 1); + return texture; + } + + private static int mapFormat(TextureFormat format) { + return switch (format) { + case RGBA8 -> VK_FORMAT_R8G8B8A8_UNORM; + case RED8 -> VK_FORMAT_R8_UNORM; + case RED8I -> VK_FORMAT_R8_SINT; + case DEPTH32 -> VK_FORMAT_D32_SFLOAT; + }; + } + + private static int resolveUsage(int textureUsage, TextureFormat format) { + int flags = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + + if ((textureUsage & GpuTexture.USAGE_TEXTURE_BINDING) != 0) { + flags |= VK_IMAGE_USAGE_SAMPLED_BIT; + } + if ((textureUsage & GpuTexture.USAGE_RENDER_ATTACHMENT) != 0) { + if (format.hasDepthAspect()) { + flags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; + } else { + flags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + } + } + + return flags; + } + + @Override + public GpuTextureView createTextureView(GpuTexture texture) { + return new VulkanGpuTextureView((VulkanGpuTexture) texture, 0, texture.getMipLevels()); + } + + @Override + public GpuTextureView createTextureView(GpuTexture texture, int baseMipLevel, int levelCount) { + return new VulkanGpuTextureView((VulkanGpuTexture) texture, baseMipLevel, levelCount); + } + + @Override + public VulkanGpuBuffer createBuffer(java.util.function.Supplier label, + int usage, + int size) { + String name = label != null ? label.get() : "unnamed-buffer"; + return new VulkanGpuBuffer(this, name, usage, size); + } + + @Override + public VulkanGpuBuffer createBuffer(java.util.function.Supplier label, + int usage, + java.nio.ByteBuffer initialData) { + String name = label != null ? label.get() : "unnamed-buffer"; + VulkanGpuBuffer buffer = new VulkanGpuBuffer(this, name, usage, initialData.remaining()); + buffer.upload(initialData); + return buffer; + } + + @Override + public String getImplementationInformation() { + return "VulkanMod Vulkan backend (WIP)"; + } + + @Override + public List getLastDebugMessages() { + return Collections.emptyList(); + } + + @Override + public boolean isDebuggingEnabled() { + return debugVerbosity > 0 || debugSync || debugLabels; + } + + @Override + public String getVendor() { + return DeviceManager.deviceProperties != null + ? Integer.toUnsignedString(DeviceManager.deviceProperties.vendorID(), 16) + : "unknown"; + } + + @Override + public String getBackendName() { + return "Vulkan"; + } + + @Override + public String getVersion() { + return "1.2"; + } + + @Override + public String getRenderer() { + return DeviceManager.deviceProperties != null + ? DeviceManager.deviceProperties.deviceNameString() + : "unknown"; + } + + @Override + public int getMaxTextureSize() { + return DeviceManager.deviceProperties != null + ? DeviceManager.deviceProperties.limits().maxImageDimension2D() + : 0; + } + + @Override + public int getUniformOffsetAlignment() { + return DeviceManager.deviceProperties != null + ? (int) DeviceManager.deviceProperties.limits().minUniformBufferOffsetAlignment() + : 256; + } + + @Override + public CompiledRenderPipeline precompilePipeline(RenderPipeline pipeline) { + throw new UnsupportedOperationException("precompilePipeline is not implemented yet"); + } + + @Override + public CompiledRenderPipeline precompilePipeline(RenderPipeline pipeline, + BiFunction shaderSourceGetter) { + throw new UnsupportedOperationException("precompilePipeline is not implemented yet"); + } + + @Override + public void clearPipelineCache() { + // TODO: integrate with PipelineManager once the Vulkan pipeline cache is hooked up. + } + + @Override + public List getEnabledExtensions() { + return Collections.emptyList(); + } + + @Override + public void close() { + Renderer.getInstance().cleanUpResources(); + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuFence.java b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuFence.java new file mode 100644 index 000000000..fb5d3fb85 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuFence.java @@ -0,0 +1,50 @@ +package net.vulkanmod.vulkan.blaze; + +import com.mojang.blaze3d.buffers.GpuFence; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Lightweight fence placeholder backed by a {@link CompletableFuture}. The + * implementation will be updated to use Vulkan timeline semaphores once the + * command encoder is fully functional. + */ +public final class VulkanGpuFence implements GpuFence { + + private final CompletableFuture signal = new CompletableFuture<>(); + private final AtomicBoolean closed = new AtomicBoolean(false); + + public void signal() { + signal.complete(null); + } + + @Override + public void close() { + if (closed.compareAndSet(false, true)) { + signal.complete(null); + } + } + + @Override + public boolean awaitCompletion(long nanosTimeout) { + if (signal.isDone()) { + return true; + } + + if (nanosTimeout == 0L) { + return signal.isDone(); + } + + try { + if (nanosTimeout < 0L) { + signal.get(); + } else { + signal.get(nanosTimeout, java.util.concurrent.TimeUnit.NANOSECONDS); + } + return true; + } catch (Exception ignored) { + return false; + } + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuTexture.java b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuTexture.java new file mode 100644 index 000000000..fb389a049 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuTexture.java @@ -0,0 +1,54 @@ +package net.vulkanmod.vulkan.blaze; + +import com.mojang.blaze3d.textures.GpuTexture; +import com.mojang.blaze3d.textures.TextureFormat; +import net.vulkanmod.vulkan.texture.VulkanImage; + +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * WIP texture wrapper. The actual Vulkan image creation and upload code will be + * connected once the command encoder is capable of recording the necessary operations. + */ +public final class VulkanGpuTexture extends GpuTexture { + + private final VulkanGpuDevice device; + private final AtomicBoolean closed = new AtomicBoolean(false); + private VulkanImage image; + + VulkanGpuTexture(VulkanGpuDevice device, + int usage, + String label, + TextureFormat format, + int width, + int height, + int depthOrLayers, + int mipLevels) { + super(usage, label, format, width, height, depthOrLayers, mipLevels); + this.device = device; + } + + public VulkanGpuDevice device() { + return device; + } + + public void attachImage(VulkanImage image) { + this.image = image; + } + + public VulkanImage image() { + return image; + } + + @Override + public void close() { + if (closed.compareAndSet(false, true) && image != null) { + image.free(); + } + } + + @Override + public boolean isClosed() { + return closed.get(); + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuTextureView.java b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuTextureView.java new file mode 100644 index 000000000..20b69cbfb --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanGpuTextureView.java @@ -0,0 +1,35 @@ +package net.vulkanmod.vulkan.blaze; + +import com.mojang.blaze3d.textures.GpuTexture; +import com.mojang.blaze3d.textures.GpuTextureView; + +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Placeholder texture view implementation. Once the backing command encoder + * supports render pass creation we will expose the actual Vulkan image view. + */ +public final class VulkanGpuTextureView extends GpuTextureView { + + private final VulkanGpuTexture texture; + private final AtomicBoolean closed = new AtomicBoolean(false); + + VulkanGpuTextureView(VulkanGpuTexture texture, int baseMip, int mipLevels) { + super(texture, baseMip, mipLevels); + this.texture = texture; + } + + public VulkanGpuTexture textureHandle() { + return texture; + } + + @Override + public void close() { + closed.set(true); + } + + @Override + public boolean isClosed() { + return closed.get(); + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/blaze/VulkanRenderPass.java b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanRenderPass.java new file mode 100644 index 000000000..6cde65938 --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanRenderPass.java @@ -0,0 +1,129 @@ +package net.vulkanmod.vulkan.blaze; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.buffers.GpuBufferSlice; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.systems.RenderPass; +import com.mojang.blaze3d.textures.GpuTextureView; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.vulkanmod.vulkan.Renderer; +import net.vulkanmod.vulkan.framebuffer.Framebuffer; +import net.vulkanmod.vulkan.framebuffer.RenderPass.Builder; +import org.lwjgl.vulkan.VkCommandBuffer; + +import java.util.Collection; +import java.util.Objects; +import java.util.function.Supplier; + +/** + * Vulkan-backed RenderPass driven by the existing {@link Builder}. Many draw + * operations are still pending; for now we only set up descriptor bindings and + * keep track of state. + */ +final class VulkanRenderPass implements RenderPass { + + private final VulkanCommandEncoder encoder; + private final VulkanRenderPassState state; + + private boolean closed = false; + + VulkanRenderPass(VulkanCommandEncoder encoder, VulkanRenderPassState state) { + this.encoder = encoder; + this.state = state; + state.begin(Renderer.getCommandBuffer()); + } + + private static UnsupportedOperationException nyi(String method) { + return new UnsupportedOperationException("RenderPass#" + method + " is not implemented yet"); + } + + VulkanRenderPassState state() { + return state; + } + + void begin(VkCommandBuffer commandBuffer) { + state.begin(commandBuffer); + } + + void end(VkCommandBuffer commandBuffer) { + if (!closed) { + Renderer.getInstance().endRenderPass(commandBuffer); + closed = true; + } + } + + @Override + public void pushDebugGroup(Supplier messageFactory) { + // TODO integrate with VK_EXT_debug_utils + } + + @Override + public void popDebugGroup() { + } + + @Override + public void setPipeline(RenderPipeline pipeline) { + throw nyi("setPipeline"); + } + + @Override + public void bindSampler(String name, GpuTextureView view) { + // descriptor binding will be implemented later + } + + @Override + public void setUniform(String name, GpuBuffer buffer) { + // descriptor binding will be implemented later + } + + @Override + public void setUniform(String name, GpuBufferSlice slice) { + // descriptor binding will be implemented later + } + + @Override + public void enableScissor(int x, int y, int width, int height) { + Renderer.setScissor(x, y, width, height); + } + + @Override + public void disableScissor() { + Framebuffer framebuffer = state.framebuffer.handle(); + Renderer.setScissor(0, 0, framebuffer.getWidth(), framebuffer.getHeight()); + } + + @Override + public void setVertexBuffer(int slot, GpuBuffer buffer) { + throw nyi("setVertexBuffer"); + } + + @Override + public void setIndexBuffer(GpuBuffer buffer, VertexFormat.IndexType type) { + throw nyi("setIndexBuffer"); + } + + @Override + public void drawIndexed(int indexCount, int instanceCount, int firstIndex, int baseVertex) { + throw nyi("drawIndexed"); + } + + @Override + public void drawMultipleIndexed(Collection> draws, + GpuBuffer indirectBuffer, + VertexFormat.IndexType type, + Collection boundSamplers, + T shaderState) { + throw nyi("drawMultipleIndexed"); + } + + @Override + public void draw(int vertexCount, int instanceCount) { + throw nyi("draw"); + } + + @Override + public void close() { + end(Renderer.getCommandBuffer()); + encoder.onRenderPassClosed(); + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/blaze/VulkanRenderPassState.java b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanRenderPassState.java new file mode 100644 index 000000000..cae7fab8b --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/blaze/VulkanRenderPassState.java @@ -0,0 +1,104 @@ +package net.vulkanmod.vulkan.blaze; + +import com.mojang.blaze3d.textures.GpuTextureView; +import net.minecraft.util.ARGB; +import net.vulkanmod.vulkan.framebuffer.Framebuffer; +import net.vulkanmod.vulkan.framebuffer.RenderPass; +import net.vulkanmod.vulkan.util.VUtil; +import org.lwjgl.vulkan.VkClearAttachment; +import org.lwjgl.vulkan.VkClearRect; +import org.lwjgl.vulkan.VkCommandBuffer; + +import java.lang.foreign.Arena; +import java.util.OptionalDouble; +import java.util.OptionalInt; + +import static org.lwjgl.vulkan.VK10.VK_ATTACHMENT_LOAD_OP_CLEAR; +import static org.lwjgl.vulkan.VK10.VK_ATTACHMENT_LOAD_OP_LOAD; +import static org.lwjgl.vulkan.VK10.VK_IMAGE_ASPECT_COLOR_BIT; +import static org.lwjgl.vulkan.VK10.VK_IMAGE_ASPECT_DEPTH_BIT; +import static org.lwjgl.vulkan.VK10.vkCmdClearAttachments; + +final class VulkanRenderPassState { + final VulkanFramebuffer framebuffer; + final RenderPass renderPass; + + private final OptionalInt colorClear; + private final OptionalDouble depthClear; + + private VulkanRenderPassState(VulkanFramebuffer framebuffer, RenderPass renderPass, + OptionalInt colorClear, OptionalDouble depthClear) { + this.framebuffer = framebuffer; + this.renderPass = renderPass; + this.colorClear = colorClear; + this.depthClear = depthClear; + } + + static VulkanRenderPassState create(VulkanFramebuffer framebuffer, + GpuTextureView colorView, + OptionalInt colorLevel, + GpuTextureView depthView, + OptionalDouble clearDepth) { + Framebuffer fb = framebuffer.handle(); + RenderPass.Builder builder = RenderPass.builder(fb); + + if (builder.getColorAttachmentInfo() != null) { + builder.getColorAttachmentInfo().setLoadOp(VK_ATTACHMENT_LOAD_OP_LOAD); + } + if (builder.getDepthAttachmentInfo() != null) { + builder.getDepthAttachmentInfo().setLoadOp(VK_ATTACHMENT_LOAD_OP_LOAD); + } + + RenderPass renderPass = builder.build(); + return new VulkanRenderPassState(framebuffer, renderPass, colorLevel, clearDepth); + } + + void begin(VkCommandBuffer commandBuffer) { + framebuffer.handle().beginRenderPass(commandBuffer, renderPass); + + if (colorClear.isPresent() || depthClear.isPresent()) { + try (Arena arena = Arena.ofConfined()) { + int attachmentCount = (colorClear.isPresent() ? 1 : 0) + (depthClear.isPresent() ? 1 : 0); + VkClearAttachment.Buffer attachments = VUtil.structBuffer( + arena, + VkClearAttachment.SIZEOF, + VkClearAttachment.ALIGNOF, + attachmentCount, + VkClearAttachment::create + ); + int index = 0; + + if (colorClear.isPresent()) { + VkClearAttachment colorAttachment = attachments.get(index++); + colorAttachment.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT); + colorAttachment.colorAttachment(0); + int argb = colorClear.getAsInt(); + colorAttachment.clearValue().color().float32(0, ARGB.redFloat(argb)); + colorAttachment.clearValue().color().float32(1, ARGB.greenFloat(argb)); + colorAttachment.clearValue().color().float32(2, ARGB.blueFloat(argb)); + colorAttachment.clearValue().color().float32(3, ARGB.alphaFloat(argb)); + } + + if (depthClear.isPresent()) { + VkClearAttachment depthAttachment = attachments.get(index); + depthAttachment.aspectMask(VK_IMAGE_ASPECT_DEPTH_BIT); + depthAttachment.clearValue().depthStencil().set((float) depthClear.getAsDouble(), 0); + } + + VkClearRect.Buffer rect = VUtil.structBuffer( + arena, + VkClearRect.SIZEOF, + VkClearRect.ALIGNOF, + 1, + VkClearRect::create + ); + rect.get(0).rect().offset().set(0, 0); + rect.get(0).rect().extent().set(framebuffer.handle().getWidth(), framebuffer.handle().getHeight()); + rect.get(0).baseArrayLayer(0); + rect.get(0).layerCount(1); + + vkCmdClearAttachments(commandBuffer, attachments, rect); + } + } + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/device/Device.java b/src/main/java/net/vulkanmod/vulkan/device/Device.java index da850d3b9..9f2ae25db 100644 --- a/src/main/java/net/vulkanmod/vulkan/device/Device.java +++ b/src/main/java/net/vulkanmod/vulkan/device/Device.java @@ -1,10 +1,7 @@ package net.vulkanmod.vulkan.device; -import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryStack; import org.lwjgl.vulkan.*; -import oshi.SystemInfo; -import oshi.hardware.CentralProcessor; import java.nio.IntBuffer; import java.util.HashSet; @@ -19,21 +16,18 @@ import static org.lwjgl.vulkan.VK11.vkGetPhysicalDeviceFeatures2; public class Device { - final VkPhysicalDevice physicalDevice; - final VkPhysicalDeviceProperties properties; - - private final int vendorId; public final String vendorIdString; public final String deviceName; public final String driverVersion; public final String vkVersion; - public final VkPhysicalDeviceFeatures2 availableFeatures; public final VkPhysicalDeviceVulkan11Features availableFeatures11; + final VkPhysicalDevice physicalDevice; + final VkPhysicalDeviceProperties properties; + private final int vendorId; // public final VkPhysicalDeviceVulkan13Features availableFeatures13; // public final boolean vulkan13Support; - private boolean drawIndirectSupported; public Device(VkPhysicalDevice device) { diff --git a/src/main/java/net/vulkanmod/vulkan/device/DeviceManager.java b/src/main/java/net/vulkanmod/vulkan/device/DeviceManager.java index 18fd202a0..62a493a04 100644 --- a/src/main/java/net/vulkanmod/vulkan/device/DeviceManager.java +++ b/src/main/java/net/vulkanmod/vulkan/device/DeviceManager.java @@ -171,6 +171,21 @@ public static void createLogicalDevice() { deviceVulkan11Features.sType$Default(); deviceVulkan11Features.shaderDrawParameters(device.isDrawIndirectSupported()); + VkPhysicalDeviceBufferDeviceAddressFeatures bufferDeviceAddressFeatures = VkPhysicalDeviceBufferDeviceAddressFeatures.calloc(stack); + bufferDeviceAddressFeatures.sType$Default(); + bufferDeviceAddressFeatures.bufferDeviceAddress(true); + deviceVulkan11Features.pNext(bufferDeviceAddressFeatures.address()); + + VkPhysicalDeviceAccelerationStructureFeaturesKHR accelerationStructureFeatures = VkPhysicalDeviceAccelerationStructureFeaturesKHR.calloc(stack); + accelerationStructureFeatures.sType$Default(); + accelerationStructureFeatures.accelerationStructure(true); + bufferDeviceAddressFeatures.pNext(accelerationStructureFeatures.address()); + + VkPhysicalDeviceRayTracingPipelineFeaturesKHR rayTracingPipelineFeatures = VkPhysicalDeviceRayTracingPipelineFeaturesKHR.calloc(stack); + rayTracingPipelineFeatures.sType$Default(); + rayTracingPipelineFeatures.rayTracingPipeline(true); + accelerationStructureFeatures.pNext(rayTracingPipelineFeatures.address()); + VkPhysicalDeviceFeatures2 deviceFeatures = VkPhysicalDeviceFeatures2.calloc(stack); deviceFeatures.sType$Default(); deviceFeatures.features().samplerAnisotropy(device.availableFeatures.features().samplerAnisotropy()); @@ -196,7 +211,7 @@ public static void createLogicalDevice() { dynamicRenderingFeaturesKHR.sType$Default(); dynamicRenderingFeaturesKHR.dynamicRendering(true); - deviceVulkan11Features.pNext(dynamicRenderingFeaturesKHR.address()); + rayTracingPipelineFeatures.pNext(dynamicRenderingFeaturesKHR.address()); // //Vulkan 1.3 dynamic rendering // VkPhysicalDeviceVulkan13Features deviceVulkan13Features = VkPhysicalDeviceVulkan13Features.calloc(stack); diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java index 8a2d5ad09..d71f3e509 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/Framebuffer.java @@ -5,38 +5,48 @@ import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.texture.VulkanImage; +import net.vulkanmod.vulkan.util.VUtil; import org.apache.commons.lang3.Validate; -import org.lwjgl.system.MemoryStack; -import org.lwjgl.vulkan.*; +import org.lwjgl.vulkan.VkCommandBuffer; +import org.lwjgl.vulkan.VkFramebufferCreateInfo; +import org.lwjgl.vulkan.VkRect2D; +import org.lwjgl.vulkan.VkDevice; +import org.lwjgl.vulkan.VkViewport; +import java.lang.foreign.Arena; import java.nio.LongBuffer; import java.util.Arrays; import static net.vulkanmod.vulkan.Vulkan.DYNAMIC_RENDERING; -import static org.lwjgl.vulkan.VK10.*; +import static org.lwjgl.vulkan.VK10.VK_FORMAT_R8G8B8A8_UNORM; +import static org.lwjgl.vulkan.VK10.VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; +import static org.lwjgl.vulkan.VK10.VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; +import static org.lwjgl.vulkan.VK10.VK_IMAGE_USAGE_SAMPLED_BIT; +import static org.lwjgl.vulkan.VK10.VK_SUCCESS; +import static org.lwjgl.vulkan.VK10.vkCmdSetScissor; +import static org.lwjgl.vulkan.VK10.vkCmdSetViewport; +import static org.lwjgl.vulkan.VK10.vkCreateFramebuffer; +import static org.lwjgl.vulkan.VK10.vkDestroyFramebuffer; public class Framebuffer { public static final int DEFAULT_FORMAT = VK_FORMAT_R8G8B8A8_UNORM; // private long id; - + private final Reference2LongArrayMap renderpassToFramebufferMap = new Reference2LongArrayMap<>(); protected int format; protected int depthFormat; protected int width, height; protected boolean linearFiltering; protected boolean depthLinearFiltering; protected int attachmentCount; - + protected VulkanImage depthAttachment; boolean hasColorAttachment; boolean hasDepthAttachment; - private VulkanImage colorAttachment; - protected VulkanImage depthAttachment; - - private final Reference2LongArrayMap renderpassToFramebufferMap = new Reference2LongArrayMap<>(); //SwapChain - protected Framebuffer() {} + protected Framebuffer() { + } public Framebuffer(Builder builder) { this.format = builder.format; @@ -56,6 +66,14 @@ public Framebuffer(Builder builder) { } } + public static Builder builder(int width, int height, int colorAttachments, boolean hasDepthAttachment) { + return new Builder(width, height, colorAttachments, hasDepthAttachment); + } + + public static Builder builder(VulkanImage colorAttachment, VulkanImage depthAttachment) { + return new Builder(colorAttachment, depthAttachment); + } + public void createImages() { if (this.hasColorAttachment) { this.colorAttachment = VulkanImage.builder(this.width, this.height) @@ -85,21 +103,25 @@ public void resize(int newWidth, int newHeight) { } private long createFramebuffer(RenderPass renderPass) { - - try (MemoryStack stack = MemoryStack.stackPush()) { - - LongBuffer attachments; - if (colorAttachment != null && depthAttachment != null) { - attachments = stack.longs(colorAttachment.getImageView(), depthAttachment.getImageView()); - } else if (colorAttachment != null) { - attachments = stack.longs(colorAttachment.getImageView()); - } else { - throw new IllegalStateException(); + try (Arena arena = Arena.ofConfined()) { + LongBuffer attachments = colorAttachment != null && depthAttachment != null + ? VUtil.longBuffer(arena, colorAttachment.getImageView(), depthAttachment.getImageView()) + : colorAttachment != null + ? VUtil.longBuffer(arena, colorAttachment.getImageView()) + : null; + + if (attachments == null) { + throw new IllegalStateException("Framebuffer must have at least one attachment"); } - LongBuffer pFramebuffer = stack.mallocLong(1); + LongBuffer pFramebuffer = VUtil.allocateLongBuffer(arena, 1); - VkFramebufferCreateInfo framebufferInfo = VkFramebufferCreateInfo.calloc(stack); + VkFramebufferCreateInfo framebufferInfo = VUtil.struct( + arena, + VkFramebufferCreateInfo.SIZEOF, + VkFramebufferCreateInfo.ALIGNOF, + VkFramebufferCreateInfo::create + ); framebufferInfo.sType$Default(); framebufferInfo.renderPass(renderPass.getId()); framebufferInfo.width(this.width); @@ -107,7 +129,7 @@ private long createFramebuffer(RenderPass renderPass) { framebufferInfo.layers(1); framebufferInfo.pAttachments(attachments); - if (VK10.vkCreateFramebuffer(Vulkan.getVkDevice(), framebufferInfo, null, pFramebuffer) != VK_SUCCESS) { + if (vkCreateFramebuffer(Vulkan.getVkDevice(), framebufferInfo, null, pFramebuffer) != VK_SUCCESS) { throw new RuntimeException("Failed to create framebuffer"); } @@ -115,12 +137,16 @@ private long createFramebuffer(RenderPass renderPass) { } } - public void beginRenderPass(VkCommandBuffer commandBuffer, RenderPass renderPass, MemoryStack stack) { + public void beginRenderPass(VkCommandBuffer commandBuffer, RenderPass renderPass) { if (!DYNAMIC_RENDERING) { long framebufferId = this.getFramebufferId(renderPass); - renderPass.beginRenderPass(commandBuffer, framebufferId, stack); + try (Arena arena = Arena.ofConfined()) { + renderPass.beginRenderPass(commandBuffer, framebufferId, arena); + } } else { - renderPass.beginDynamicRendering(commandBuffer, stack); + try (Arena arena = Arena.ofConfined()) { + renderPass.beginDynamicRendering(commandBuffer, arena, this); + } } Renderer.getInstance().setBoundRenderPass(renderPass); @@ -134,24 +160,40 @@ protected long getFramebufferId(RenderPass renderPass) { return this.renderpassToFramebufferMap.computeIfAbsent(renderPass, renderPass1 -> createFramebuffer(renderPass)); } - public VkViewport.Buffer viewport(MemoryStack stack) { - VkViewport.Buffer viewport = VkViewport.malloc(1, stack); - viewport.x(0.0f); - viewport.y(this.height); - viewport.width(this.width); - viewport.height(-this.height); - viewport.minDepth(0.0f); - viewport.maxDepth(1.0f); - - return viewport; + public void applyViewport(VkCommandBuffer commandBuffer) { + try (Arena arena = Arena.ofConfined()) { + VkViewport.Buffer viewport = VUtil.structBuffer( + arena, + VkViewport.SIZEOF, + VkViewport.ALIGNOF, + 1, + VkViewport::create + ); + viewport.x(0.0f); + viewport.y(this.height); + viewport.width(this.width); + viewport.height(-this.height); + viewport.minDepth(0.0f); + viewport.maxDepth(1.0f); + + vkCmdSetViewport(commandBuffer, 0, viewport); + } } - public VkRect2D.Buffer scissor(MemoryStack stack) { - VkRect2D.Buffer scissor = VkRect2D.malloc(1, stack); - scissor.offset().set(0, 0); - scissor.extent().set(this.width, this.height); - - return scissor; + public void applyScissor(VkCommandBuffer commandBuffer) { + try (Arena arena = Arena.ofConfined()) { + VkRect2D.Buffer scissor = VUtil.structBuffer( + arena, + VkRect2D.SIZEOF, + VkRect2D.ALIGNOF, + 1, + VkRect2D::create + ); + scissor.offset().set(0, 0); + scissor.extent().set(this.width, this.height); + + vkCmdSetScissor(commandBuffer, 0, scissor); + } } public void cleanUp() { @@ -207,14 +249,6 @@ public int getDepthFormat() { return this.depthFormat; } - public static Builder builder(int width, int height, int colorAttachments, boolean hasDepthAttachment) { - return new Builder(width, height, colorAttachments, hasDepthAttachment); - } - - public static Builder builder(VulkanImage colorAttachment, VulkanImage depthAttachment) { - return new Builder(colorAttachment, depthAttachment); - } - public static class Builder { final boolean createImages; final int width, height; @@ -223,7 +257,7 @@ public static class Builder { VulkanImage colorAttachment; VulkanImage depthAttachment; -// int colorAttachments; + // int colorAttachments; boolean hasColorAttachment; boolean hasDepthAttachment; diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java index 589f00c21..94985b3c5 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/RenderPass.java @@ -4,19 +4,32 @@ import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.memory.MemoryManager; -import org.lwjgl.system.MemoryStack; -import org.lwjgl.vulkan.*; - +import net.vulkanmod.vulkan.texture.VulkanImage; +import net.vulkanmod.vulkan.util.VUtil; +import org.lwjgl.vulkan.KHRDynamicRendering; +import org.lwjgl.vulkan.VkAttachmentDescription; +import org.lwjgl.vulkan.VkAttachmentReference; +import org.lwjgl.vulkan.VkClearValue; +import org.lwjgl.vulkan.VkCommandBuffer; +import org.lwjgl.vulkan.VkRect2D; +import org.lwjgl.vulkan.VkRenderPassBeginInfo; +import org.lwjgl.vulkan.VkRenderPassCreateInfo; +import org.lwjgl.vulkan.VkRenderingAttachmentInfo; +import org.lwjgl.vulkan.VkRenderingInfo; +import org.lwjgl.vulkan.VkSubpassDependency; +import org.lwjgl.vulkan.VkSubpassDescription; +import org.lwjgl.vulkan.VkViewport; + +import java.lang.foreign.Arena; import java.nio.LongBuffer; import static org.lwjgl.vulkan.KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; import static org.lwjgl.vulkan.VK10.*; public class RenderPass { + final int attachmentCount; Framebuffer framebuffer; long id; - - final int attachmentCount; AttachmentInfo colorAttachmentInfo; AttachmentInfo depthAttachmentInfo; @@ -39,92 +52,139 @@ public RenderPass(Framebuffer framebuffer, AttachmentInfo colorAttachmentInfo, A } - private void createRenderPass() { - - try (MemoryStack stack = MemoryStack.stackPush()) { - VkAttachmentDescription.Buffer attachments = VkAttachmentDescription.calloc(attachmentCount, stack); - VkAttachmentReference.Buffer attachmentRefs = VkAttachmentReference.calloc(attachmentCount, stack); + public static Builder builder(Framebuffer framebuffer) { + return new Builder(framebuffer); + } - VkSubpassDescription.Buffer subpass = VkSubpassDescription.calloc(1, stack); + private void createRenderPass() { + try (Arena arena = Arena.ofConfined()) { + VkAttachmentDescription.Buffer attachments = VUtil.structBuffer( + arena, + VkAttachmentDescription.SIZEOF, + VkAttachmentDescription.ALIGNOF, + attachmentCount, + VkAttachmentDescription::create + ); + VkAttachmentReference.Buffer attachmentRefs = attachmentCount > 0 + ? VUtil.structBuffer(arena, VkAttachmentReference.SIZEOF, VkAttachmentReference.ALIGNOF, attachmentCount, VkAttachmentReference::create) + : null; + + VkSubpassDescription.Buffer subpass = VUtil.structBuffer( + arena, + VkSubpassDescription.SIZEOF, + VkSubpassDescription.ALIGNOF, + 1, + VkSubpassDescription::create + ); subpass.pipelineBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS); - int i = 0; + int attachmentIndex = 0; - // Color attachment if (colorAttachmentInfo != null) { - VkAttachmentDescription colorAttachment = attachments.get(i); + VkAttachmentDescription colorAttachment = attachments.get(attachmentIndex); colorAttachment.format(colorAttachmentInfo.format) - .samples(VK_SAMPLE_COUNT_1_BIT) - .loadOp(colorAttachmentInfo.loadOp) - .storeOp(colorAttachmentInfo.storeOp) - .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) - .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) - .initialLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) - .finalLayout(colorAttachmentInfo.finalLayout); - - VkAttachmentReference colorAttachmentRef = attachmentRefs.get(0) - .attachment(0) - .layout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + .samples(VK_SAMPLE_COUNT_1_BIT) + .loadOp(colorAttachmentInfo.loadOp) + .storeOp(colorAttachmentInfo.storeOp) + .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) + .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) + .initialLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) + .finalLayout(colorAttachmentInfo.finalLayout); + + VkAttachmentReference.Buffer colorRef = VUtil.structBuffer( + arena, + VkAttachmentReference.SIZEOF, + VkAttachmentReference.ALIGNOF, + 1, + VkAttachmentReference::create + ); + colorRef.get(0) + .attachment(attachmentIndex) + .layout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); subpass.colorAttachmentCount(1); - subpass.pColorAttachments(VkAttachmentReference.calloc(1, stack).put(0, colorAttachmentRef)); - - ++i; + subpass.pColorAttachments(colorRef); + attachmentIndex++; } - // Depth-Stencil attachment if (depthAttachmentInfo != null) { - VkAttachmentDescription depthAttachment = attachments.get(i); + VkAttachmentDescription depthAttachment = attachments.get(attachmentIndex); depthAttachment.format(depthAttachmentInfo.format) - .samples(VK_SAMPLE_COUNT_1_BIT) - .loadOp(depthAttachmentInfo.loadOp) - .storeOp(depthAttachmentInfo.storeOp) - .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) - .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) - .initialLayout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) - .finalLayout(depthAttachmentInfo.finalLayout); - - VkAttachmentReference depthAttachmentRef = attachmentRefs.get(1) - .attachment(1) - .layout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); - - subpass.pDepthStencilAttachment(depthAttachmentRef); + .samples(VK_SAMPLE_COUNT_1_BIT) + .loadOp(depthAttachmentInfo.loadOp) + .storeOp(depthAttachmentInfo.storeOp) + .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE) + .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE) + .initialLayout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) + .finalLayout(depthAttachmentInfo.finalLayout); + + VkAttachmentReference.Buffer depthRef = VUtil.structBuffer( + arena, + VkAttachmentReference.SIZEOF, + VkAttachmentReference.ALIGNOF, + 1, + VkAttachmentReference::create + ); + depthRef.get(0) + .attachment(attachmentIndex) + .layout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + + subpass.pDepthStencilAttachment(depthRef.get(0)); + attachmentIndex++; } - VkRenderPassCreateInfo renderPassInfo = VkRenderPassCreateInfo.calloc(stack); - renderPassInfo.sType$Default() - .pAttachments(attachments) - .pSubpasses(subpass); + VkRenderPassCreateInfo renderPassInfo = VUtil.struct( + arena, + VkRenderPassCreateInfo.SIZEOF, + VkRenderPassCreateInfo.ALIGNOF, + VkRenderPassCreateInfo::create + ); + renderPassInfo.sType$Default(); + renderPassInfo.pAttachments(attachments); + renderPassInfo.pSubpasses(subpass); - //Layout transition subpass depency - switch (colorAttachmentInfo.finalLayout) { - case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR -> { - VkSubpassDependency.Buffer subpassDependencies = VkSubpassDependency.calloc(1, stack); - subpassDependencies.get(0) + if (colorAttachmentInfo != null) { + switch (colorAttachmentInfo.finalLayout) { + case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR -> { + VkSubpassDependency.Buffer dependency = VUtil.structBuffer( + arena, + VkSubpassDependency.SIZEOF, + VkSubpassDependency.ALIGNOF, + 1, + VkSubpassDependency::create + ); + dependency.get(0) .srcSubpass(VK_SUBPASS_EXTERNAL) .dstSubpass(0) .srcStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) .dstStageMask(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT) .srcAccessMask(0) .dstAccessMask(0); - - renderPassInfo.pDependencies(subpassDependencies); - } - case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL -> { - VkSubpassDependency.Buffer subpassDependencies = VkSubpassDependency.calloc(1, stack); - subpassDependencies.get(0) + renderPassInfo.pDependencies(dependency); + } + case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL -> { + VkSubpassDependency.Buffer dependency = VUtil.structBuffer( + arena, + VkSubpassDependency.SIZEOF, + VkSubpassDependency.ALIGNOF, + 1, + VkSubpassDependency::create + ); + dependency.get(0) .srcSubpass(0) .dstSubpass(VK_SUBPASS_EXTERNAL) .srcStageMask(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) .dstStageMask(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) .srcAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT) .dstAccessMask(VK_ACCESS_SHADER_READ_BIT); - - renderPassInfo.pDependencies(subpassDependencies); + renderPassInfo.pDependencies(dependency); + } + default -> { + } } } - LongBuffer pRenderPass = stack.mallocLong(1); + LongBuffer pRenderPass = VUtil.allocateLongBuffer(arena, 1); if (vkCreateRenderPass(Vulkan.getVkDevice(), renderPassInfo, null, pRenderPass) != VK_SUCCESS) { throw new RuntimeException("Failed to create render pass"); @@ -134,27 +194,52 @@ private void createRenderPass() { } } - public void beginRenderPass(VkCommandBuffer commandBuffer, long framebufferId, MemoryStack stack) { + public void beginRenderPass(VkCommandBuffer commandBuffer, long framebufferId, Arena arena) { if (colorAttachmentInfo != null - && framebuffer.getColorAttachment().getCurrentLayout() != VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) - framebuffer.getColorAttachment().transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + && framebuffer.getColorAttachment().getCurrentLayout() != VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { + VulkanImage.transitionImageLayout(arena, commandBuffer, framebuffer.getColorAttachment(), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + } if (depthAttachmentInfo != null - && framebuffer.getDepthAttachment().getCurrentLayout() != VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) - framebuffer.getDepthAttachment().transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + && framebuffer.getDepthAttachment().getCurrentLayout() != VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { + VulkanImage.transitionImageLayout(arena, commandBuffer, framebuffer.getDepthAttachment(), VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); + } - VkRenderPassBeginInfo renderPassInfo = VkRenderPassBeginInfo.calloc(stack); + VkRenderPassBeginInfo renderPassInfo = VUtil.struct( + arena, + VkRenderPassBeginInfo.SIZEOF, + VkRenderPassBeginInfo.ALIGNOF, + VkRenderPassBeginInfo::create + ); renderPassInfo.sType$Default(); renderPassInfo.renderPass(this.id); renderPassInfo.framebuffer(framebufferId); - VkRect2D renderArea = VkRect2D.malloc(stack); + VkRect2D renderArea = VUtil.struct( + arena, + VkRect2D.SIZEOF, + VkRect2D.ALIGNOF, + VkRect2D::create + ); renderArea.offset().set(0, 0); renderArea.extent().set(framebuffer.getWidth(), framebuffer.getHeight()); renderPassInfo.renderArea(renderArea); - VkClearValue.Buffer clearValues = VkClearValue.malloc(2, stack); - clearValues.get(0).color().float32(VRenderSystem.clearColor); + VkClearValue.Buffer clearValues = VUtil.structBuffer( + arena, + VkClearValue.SIZEOF, + VkClearValue.ALIGNOF, + 2, + VkClearValue::create + ); + float clearR = VRenderSystem.clearColor.get(0); + float clearG = VRenderSystem.clearColor.get(1); + float clearB = VRenderSystem.clearColor.get(2); + float clearA = VRenderSystem.clearColor.get(3); + clearValues.get(0).color().float32(0, clearR); + clearValues.get(0).color().float32(1, clearG); + clearValues.get(0).color().float32(2, clearB); + clearValues.get(0).color().float32(3, clearA); clearValues.get(1).depthStencil().set(1.0f, 0); renderPassInfo.pClearValues(clearValues); @@ -176,23 +261,48 @@ public void endRenderPass(VkCommandBuffer commandBuffer) { Renderer.getInstance().setBoundRenderPass(null); } - public void beginDynamicRendering(VkCommandBuffer commandBuffer, MemoryStack stack) { - VkRect2D renderArea = VkRect2D.malloc(stack); + public void beginDynamicRendering(VkCommandBuffer commandBuffer, Arena arena, Framebuffer framebuffer) { + VkRect2D renderArea = VUtil.struct( + arena, + VkRect2D.SIZEOF, + VkRect2D.ALIGNOF, + VkRect2D::create + ); renderArea.offset().set(0, 0); renderArea.extent().set(framebuffer.getWidth(), framebuffer.getHeight()); - VkClearValue.Buffer clearValues = VkClearValue.malloc(2, stack); - clearValues.get(0).color().float32(stack.floats(0.0f, 0.0f, 0.0f, 1.0f)); + VkClearValue.Buffer clearValues = VUtil.structBuffer( + arena, + VkClearValue.SIZEOF, + VkClearValue.ALIGNOF, + 2, + VkClearValue::create + ); + clearValues.get(0).color().float32(0, 0.0f); + clearValues.get(0).color().float32(1, 0.0f); + clearValues.get(0).color().float32(2, 0.0f); + clearValues.get(0).color().float32(3, 1.0f); clearValues.get(1).depthStencil().set(1.0f, 0); - VkRenderingInfo renderingInfo = VkRenderingInfo.calloc(stack); + VkRenderingInfo renderingInfo = VUtil.struct( + arena, + VkRenderingInfo.SIZEOF, + VkRenderingInfo.ALIGNOF, + VkRenderingInfo::create + ); renderingInfo.sType(KHRDynamicRendering.VK_STRUCTURE_TYPE_RENDERING_INFO_KHR); renderingInfo.renderArea(renderArea); renderingInfo.layerCount(1); // Color attachment if (colorAttachmentInfo != null) { - VkRenderingAttachmentInfo.Buffer colorAttachment = VkRenderingAttachmentInfo.calloc(1, stack); + VkRenderingAttachmentInfo.Buffer colorAttachment = VUtil.structBuffer( + arena, + VkRenderingAttachmentInfo.SIZEOF, + VkRenderingAttachmentInfo.ALIGNOF, + 1, + VkRenderingAttachmentInfo::create + ); colorAttachment.sType(KHRDynamicRendering.VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR); colorAttachment.imageView(framebuffer.getColorAttachment().getImageView()); colorAttachment.imageLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); @@ -205,7 +315,12 @@ public void beginDynamicRendering(VkCommandBuffer commandBuffer, MemoryStack sta //Depth attachment if (depthAttachmentInfo != null) { - VkRenderingAttachmentInfo depthAttachment = VkRenderingAttachmentInfo.calloc(stack); + VkRenderingAttachmentInfo depthAttachment = VUtil.struct( + arena, + VkRenderingAttachmentInfo.SIZEOF, + VkRenderingAttachmentInfo.ALIGNOF, + VkRenderingAttachmentInfo::create + ); depthAttachment.sType(KHRDynamicRendering.VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR); depthAttachment.imageView(framebuffer.getDepthAttachment().getImageView()); depthAttachment.imageLayout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); @@ -287,10 +402,6 @@ public enum Type { } } - public static Builder builder(Framebuffer framebuffer) { - return new Builder(framebuffer); - } - public static class Builder { Framebuffer framebuffer; AttachmentInfo colorAttachmentInfo; diff --git a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java index 857a80123..6063c1355 100644 --- a/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java +++ b/src/main/java/net/vulkanmod/vulkan/framebuffer/SwapChain.java @@ -33,11 +33,10 @@ public class SwapChain extends Framebuffer { private static final int defUncappedMode = checkPresentMode(VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR); private final Long2ReferenceOpenHashMap FBO_map = new Long2ReferenceOpenHashMap<>(); - + public boolean isBGRAformat; private long swapChainId = VK_NULL_HANDLE; private List swapChainImages; private VkExtent2D extent2D; - public boolean isBGRAformat; private boolean vsync = false; public SwapChain() { @@ -50,6 +49,43 @@ public SwapChain() { recreate(); } + private static VkExtent2D getExtent(VkSurfaceCapabilitiesKHR capabilities) { + + if (capabilities.currentExtent().width() != UINT32_MAX) { + return capabilities.currentExtent(); + } + + // Fallback + IntBuffer width = stackGet().ints(0); + IntBuffer height = stackGet().ints(0); + + glfwGetFramebufferSize(window, width, height); + + VkExtent2D actualExtent = VkExtent2D.mallocStack().set(width.get(0), height.get(0)); + + VkExtent2D minExtent = capabilities.minImageExtent(); + VkExtent2D maxExtent = capabilities.maxImageExtent(); + + actualExtent.width(MathUtil.clamp(minExtent.width(), maxExtent.width(), actualExtent.width())); + actualExtent.height(MathUtil.clamp(minExtent.height(), maxExtent.height(), actualExtent.height())); + + return actualExtent; + } + + private static int checkPresentMode(int... requestedModes) { + try (MemoryStack stack = MemoryStack.stackPush()) { + var a = DeviceManager.querySurfaceProperties(vkDevice.getPhysicalDevice(), stack).presentModes; + for (int dMode : requestedModes) { + for (int i = 0; i < a.capacity(); i++) { + if (a.get(i) == dMode) { + return dMode; + } + } + } + return VK_PRESENT_MODE_FIFO_KHR; // If None of the request modes exist/are supported by Driver + } + } + public void recreate() { if (this.depthAttachment != null) { this.depthAttachment.free(); @@ -285,43 +321,6 @@ private String getDisplayModeString(int requestedMode) { }; } - private static VkExtent2D getExtent(VkSurfaceCapabilitiesKHR capabilities) { - - if (capabilities.currentExtent().width() != UINT32_MAX) { - return capabilities.currentExtent(); - } - - // Fallback - IntBuffer width = stackGet().ints(0); - IntBuffer height = stackGet().ints(0); - - glfwGetFramebufferSize(window, width, height); - - VkExtent2D actualExtent = VkExtent2D.mallocStack().set(width.get(0), height.get(0)); - - VkExtent2D minExtent = capabilities.minImageExtent(); - VkExtent2D maxExtent = capabilities.maxImageExtent(); - - actualExtent.width(MathUtil.clamp(minExtent.width(), maxExtent.width(), actualExtent.width())); - actualExtent.height(MathUtil.clamp(minExtent.height(), maxExtent.height(), actualExtent.height())); - - return actualExtent; - } - - private static int checkPresentMode(int... requestedModes) { - try (MemoryStack stack = MemoryStack.stackPush()) { - var a = DeviceManager.querySurfaceProperties(vkDevice.getPhysicalDevice(), stack).presentModes; - for (int dMode : requestedModes) { - for (int i = 0; i < a.capacity(); i++) { - if (a.get(i) == dMode) { - return dMode; - } - } - } - return VK_PRESENT_MODE_FIFO_KHR; // If None of the request modes exist/are supported by Driver - } - } - public boolean isVsync() { return this.vsync; } diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java index 9e9ea353a..e2d11147c 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryManager.java @@ -29,41 +29,23 @@ import static org.lwjgl.vulkan.VK10.*; public class MemoryManager { - private static final boolean DEBUG = false; public static final long BYTES_IN_MB = 1024 * 1024; - - private static MemoryManager INSTANCE; + private static final boolean DEBUG = false; private static final long ALLOCATOR = Vulkan.getAllocator(); - private static final Long2ReferenceOpenHashMap buffers = new Long2ReferenceOpenHashMap<>(); private static final Long2ReferenceOpenHashMap images = new Long2ReferenceOpenHashMap<>(); - static int Frames; - + private static MemoryManager INSTANCE; private static long deviceMemory = 0; private static long nativeMemory = 0; - - private int currentFrame = 0; - private final ObjectArrayList[] freeableBuffers = new ObjectArrayList[Frames]; private final ObjectArrayList[] freeableImages = new ObjectArrayList[Frames]; - private final ObjectArrayList[] frameOps = new ObjectArrayList[Frames]; private final ObjectArrayList>[] segmentsToFree = new ObjectArrayList[Frames]; - + private int currentFrame = 0; //debug private ObjectArrayList[] stackTraces; - public static MemoryManager getInstance() { - return INSTANCE; - } - - public static void createInstance(int frames) { - Frames = frames; - - INSTANCE = new MemoryManager(); - } - MemoryManager() { for (int i = 0; i < Frames; ++i) { this.freeableBuffers[i] = new ObjectArrayList<>(); @@ -81,6 +63,57 @@ public static void createInstance(int frames) { } } + public static MemoryManager getInstance() { + return INSTANCE; + } + + public static void createInstance(int frames) { + Frames = frames; + + INSTANCE = new MemoryManager(); + } + + public static void addImage(VulkanImage image) { + images.putIfAbsent(image.getId(), image); + + deviceMemory += image.size; + } + + public static void MapAndCopy(long allocation, Consumer consumer) { + try (MemoryStack stack = stackPush()) { + PointerBuffer data = stack.mallocPointer(1); + + vmaMapMemory(ALLOCATOR, allocation, data); + consumer.accept(data); + vmaUnmapMemory(ALLOCATOR, allocation); + } + } + + public static void freeBuffer(long buffer, long allocation) { + vmaDestroyBuffer(ALLOCATOR, buffer, allocation); + + buffers.remove(buffer); + } + + private static void freeBuffer(Buffer.BufferInfo bufferInfo) { + vmaDestroyBuffer(ALLOCATOR, bufferInfo.id(), bufferInfo.allocation()); + + if (bufferInfo.type() == MemoryType.Type.DEVICE_LOCAL) { + deviceMemory -= bufferInfo.bufferSize(); + } else { + nativeMemory -= bufferInfo.bufferSize(); + } + + buffers.remove(bufferInfo.id()); + } + + public static void freeImage(long imageId, long allocation) { + vmaDestroyImage(ALLOCATOR, imageId, allocation); + + VulkanImage image = images.remove(imageId); + deviceMemory -= image.size; + } + public synchronized void initFrame(int frame) { this.setCurrentFrame(frame); this.freeBuffers(frame); @@ -141,8 +174,7 @@ public synchronized void createBuffer(Buffer buffer, long size, int usage, int p if ((properties & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0) { deviceMemory += size; - } - else { + } else { nativeMemory += size; } @@ -151,8 +183,8 @@ public synchronized void createBuffer(Buffer buffer, long size, int usage, int p } public void createImage(int width, int height, int mipLevels, int format, int tiling, int usage, - int memProperties, - LongBuffer pTextureImage, PointerBuffer pTextureImageMemory) { + int memProperties, + LongBuffer pTextureImage, PointerBuffer pTextureImageMemory) { try (MemoryStack stack = stackPush()) { VkImageCreateInfo imageInfo = VkImageCreateInfo.calloc(stack); @@ -185,22 +217,6 @@ public void createImage(int width, int height, int mipLevels, int format, int ti } } - public static void addImage(VulkanImage image) { - images.putIfAbsent(image.getId(), image); - - deviceMemory += image.size; - } - - public static void MapAndCopy(long allocation, Consumer consumer) { - try (MemoryStack stack = stackPush()) { - PointerBuffer data = stack.mallocPointer(1); - - vmaMapMemory(ALLOCATOR, allocation, data); - consumer.accept(data); - vmaUnmapMemory(ALLOCATOR, allocation); - } - } - public PointerBuffer Map(long allocation) { PointerBuffer data = MemoryUtil.memAllocPointer(1); @@ -209,32 +225,6 @@ public PointerBuffer Map(long allocation) { return data; } - public static void freeBuffer(long buffer, long allocation) { - vmaDestroyBuffer(ALLOCATOR, buffer, allocation); - - buffers.remove(buffer); - } - - private static void freeBuffer(Buffer.BufferInfo bufferInfo) { - vmaDestroyBuffer(ALLOCATOR, bufferInfo.id(), bufferInfo.allocation()); - - if (bufferInfo.type() == MemoryType.Type.DEVICE_LOCAL) { - deviceMemory -= bufferInfo.bufferSize(); - } - else { - nativeMemory -= bufferInfo.bufferSize(); - } - - buffers.remove(bufferInfo.id()); - } - - public static void freeImage(long imageId, long allocation) { - vmaDestroyImage(ALLOCATOR, imageId, allocation); - - VulkanImage image = images.remove(imageId); - deviceMemory -= image.size; - } - public synchronized void addToFreeable(Buffer buffer) { Buffer.BufferInfo bufferInfo = buffer.getBufferInfo(); diff --git a/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java b/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java index 15bf8d6df..d751e28c5 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/MemoryType.java @@ -7,9 +7,9 @@ import java.nio.ByteBuffer; public abstract class MemoryType { - final Type type; public final VkMemoryType vkMemoryType; public final VkMemoryHeap vkMemoryHeap; + final Type type; MemoryType(Type type, VkMemoryType vkMemoryType, VkMemoryHeap vkMemoryHeap) { this.type = type; @@ -26,7 +26,7 @@ public abstract class MemoryType { public abstract boolean mappable(); public Type getType() { - return this.type; + return this.type; } public enum Type { diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/Buffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/Buffer.java index ac8ac91e4..f13f2600c 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/Buffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/Buffer.java @@ -68,6 +68,10 @@ public long getAllocation() { return allocation; } + public void setAllocation(long allocation) { + this.allocation = allocation; + } + public long getUsedBytes() { return usedBytes; } @@ -80,24 +84,20 @@ public long getId() { return id; } - public long getBufferSize() { - return bufferSize; + public void setId(long id) { + this.id = id; } - public long getDataPtr() { - return dataPtr; + public long getBufferSize() { + return bufferSize; } public void setBufferSize(long size) { this.bufferSize = size; } - public void setId(long id) { - this.id = id; - } - - public void setAllocation(long allocation) { - this.allocation = allocation; + public long getDataPtr() { + return dataPtr; } public BufferInfo getBufferInfo() { diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndexBuffer.java index 1b2ad4c8b..fb57b9f64 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndexBuffer.java @@ -33,4 +33,4 @@ public enum IndexType { } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndirectBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndirectBuffer.java index 6b09cb0cb..b8ce2109f 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndirectBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/IndirectBuffer.java @@ -3,7 +3,6 @@ import net.vulkanmod.vulkan.Synchronization; import net.vulkanmod.vulkan.Vulkan; import net.vulkanmod.vulkan.device.DeviceManager; -import net.vulkanmod.vulkan.memory.MemoryManager; import net.vulkanmod.vulkan.memory.MemoryType; import net.vulkanmod.vulkan.queue.CommandPool; import net.vulkanmod.vulkan.queue.TransferQueue; diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/StagingBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/StagingBuffer.java index 03d764c5a..ecbec6252 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/StagingBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/StagingBuffer.java @@ -10,7 +10,7 @@ import java.nio.ByteBuffer; import static org.lwjgl.system.libc.LibCString.nmemcpy; -import static org.lwjgl.vulkan.VK10.*; +import static org.lwjgl.vulkan.VK10.VK_BUFFER_USAGE_TRANSFER_SRC_BIT; public class StagingBuffer extends Buffer { private static final long DEFAULT_SIZE = 64 * 1024 * 1024; diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/UniformBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/UniformBuffer.java index b9d102d18..804bb2c24 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/UniformBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/UniformBuffer.java @@ -9,15 +9,15 @@ public class UniformBuffer extends Buffer { private final static int MIN_OFFSET_ALIGNMENT = (int) DeviceManager.deviceProperties.limits().minUniformBufferOffsetAlignment(); - public static int getAlignedSize(int uploadSize) { - return align(uploadSize, MIN_OFFSET_ALIGNMENT); - } - public UniformBuffer(int size, MemoryType memoryType) { super(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, memoryType); this.createBuffer(size); } + public static int getAlignedSize(int uploadSize) { + return align(uploadSize, MIN_OFFSET_ALIGNMENT); + } + public void checkCapacity(int size) { if (size > this.bufferSize - this.usedBytes) { resizeBuffer((this.bufferSize + size) * 2); @@ -31,4 +31,4 @@ public void updateOffset(int alignedSize) { public long getPointer() { return this.dataPtr + usedBytes; } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/VertexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/VertexBuffer.java index fb9858c9b..edd682414 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/VertexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/VertexBuffer.java @@ -16,4 +16,4 @@ public VertexBuffer(int size, MemoryType type) { this.createBuffer(size); } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java b/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java index a05ae38cf..e1422fc1f 100644 --- a/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/memory/buffer/index/AutoIndexBuffer.java @@ -1,8 +1,8 @@ package net.vulkanmod.vulkan.memory.buffer.index; import net.vulkanmod.Initializer; -import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; import net.vulkanmod.vulkan.memory.MemoryTypes; +import net.vulkanmod.vulkan.memory.buffer.IndexBuffer; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; @@ -23,59 +23,6 @@ public AutoIndexBuffer(int vertexCount, DrawType type) { createIndexBuffer(vertexCount); } - private void createIndexBuffer(int vertexCount) { - this.vertexCount = vertexCount; - ByteBuffer buffer; - - IndexBuffer.IndexType indexType = IndexBuffer.IndexType.UINT16; - - if (vertexCount > U16_MAX_VERTEX_COUNT && - (this.drawType == DrawType.QUADS || this.drawType == DrawType.LINES)) - { - indexType = IndexBuffer.IndexType.UINT32; - } - - switch (this.drawType) { - case QUADS -> { - if (indexType == IndexBuffer.IndexType.UINT16) - buffer = genQuadIndices(vertexCount); - else { - buffer = genIntQuadIndices(vertexCount); - } - } - case TRIANGLE_FAN -> buffer = genTriangleFanIndices(vertexCount); - case TRIANGLE_STRIP -> buffer = genTriangleStripIndices(vertexCount); - case LINES -> buffer = genLinesIndices(vertexCount); - case DEBUG_LINE_STRIP -> buffer = genDebugLineStripIndices(vertexCount); - default -> throw new IllegalArgumentException("Unsupported drawType: %s".formatted(this.drawType)); - } - - int size = buffer.capacity(); - this.indexBuffer = new IndexBuffer(size, MemoryTypes.GPU_MEM, indexType); - this.indexBuffer.copyBuffer(buffer, buffer.remaining()); - - MemoryUtil.memFree(buffer); - } - - public void checkCapacity(int vertexCount) { - if(vertexCount > this.vertexCount) { - int newVertexCount = this.vertexCount * 2; - Initializer.LOGGER.info("Reallocating AutoIndexBuffer from {} to {}", this.vertexCount, newVertexCount); - - this.indexBuffer.scheduleFree(); - createIndexBuffer(newVertexCount); - } - } - - public IndexBuffer getIndexBuffer() { return this.indexBuffer; } - - public void freeBuffer() { - this.indexBuffer.scheduleFree(); - } - public int getIndexCount(int vertexCount) { - return getIndexCount(this.drawType, vertexCount); - } - public static int getIndexCount(DrawType drawType, int vertexCount) { switch (drawType) { case QUADS, LINES -> { @@ -107,7 +54,7 @@ public static ByteBuffer genQuadIndices(int vertexCount) { ShortBuffer idxs = buffer.asShortBuffer(); int j = 0; - for(int i = 0; i < vertexCount; i += 4) { + for (int i = 0; i < vertexCount; i += 4) { idxs.put(j + 0, (short) (i)); idxs.put(j + 1, (short) (i + 1)); idxs.put(j + 2, (short) (i + 2)); @@ -129,7 +76,7 @@ public static ByteBuffer genIntQuadIndices(int vertexCount) { IntBuffer idxs = buffer.asIntBuffer(); int j = 0; - for(int i = 0; i < vertexCount; i += 4) { + for (int i = 0; i < vertexCount; i += 4) { idxs.put(j + 0, (i)); idxs.put(j + 1, (i + 1)); idxs.put(j + 2, (i + 2)); @@ -151,7 +98,7 @@ public static ByteBuffer genLinesIndices(int vertexCount) { ShortBuffer idxs = buffer.asShortBuffer(); int j = 0; - for(int i = 0; i < vertexCount; i += 4) { + for (int i = 0; i < vertexCount; i += 4) { idxs.put(j + 0, (short) (i)); idxs.put(j + 1, (short) (i + 1)); idxs.put(j + 2, (short) (i + 2)); @@ -221,6 +168,61 @@ public static int roundUpToDivisible(int n, int d) { return ((n + d - 1) / d) * d; } + private void createIndexBuffer(int vertexCount) { + this.vertexCount = vertexCount; + ByteBuffer buffer; + + IndexBuffer.IndexType indexType = IndexBuffer.IndexType.UINT16; + + if (vertexCount > U16_MAX_VERTEX_COUNT && + (this.drawType == DrawType.QUADS || this.drawType == DrawType.LINES)) { + indexType = IndexBuffer.IndexType.UINT32; + } + + switch (this.drawType) { + case QUADS -> { + if (indexType == IndexBuffer.IndexType.UINT16) + buffer = genQuadIndices(vertexCount); + else { + buffer = genIntQuadIndices(vertexCount); + } + } + case TRIANGLE_FAN -> buffer = genTriangleFanIndices(vertexCount); + case TRIANGLE_STRIP -> buffer = genTriangleStripIndices(vertexCount); + case LINES -> buffer = genLinesIndices(vertexCount); + case DEBUG_LINE_STRIP -> buffer = genDebugLineStripIndices(vertexCount); + default -> throw new IllegalArgumentException("Unsupported drawType: %s".formatted(this.drawType)); + } + + int size = buffer.capacity(); + this.indexBuffer = new IndexBuffer(size, MemoryTypes.GPU_MEM, indexType); + this.indexBuffer.copyBuffer(buffer, buffer.remaining()); + + MemoryUtil.memFree(buffer); + } + + public void checkCapacity(int vertexCount) { + if (vertexCount > this.vertexCount) { + int newVertexCount = this.vertexCount * 2; + Initializer.LOGGER.info("Reallocating AutoIndexBuffer from {} to {}", this.vertexCount, newVertexCount); + + this.indexBuffer.scheduleFree(); + createIndexBuffer(newVertexCount); + } + } + + public IndexBuffer getIndexBuffer() { + return this.indexBuffer; + } + + public void freeBuffer() { + this.indexBuffer.scheduleFree(); + } + + public int getIndexCount(int vertexCount) { + return getIndexCount(this.drawType, vertexCount); + } + public enum DrawType { QUADS(7), TRIANGLE_FAN(6), diff --git a/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java b/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java index d063a42e6..66efe36b9 100644 --- a/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java +++ b/src/main/java/net/vulkanmod/vulkan/pass/DefaultMainPass.java @@ -9,26 +9,19 @@ import net.vulkanmod.vulkan.framebuffer.SwapChain; import net.vulkanmod.vulkan.texture.VTextureSelector; import net.vulkanmod.vulkan.texture.VulkanImage; -import org.lwjgl.system.MemoryStack; import org.lwjgl.vulkan.VkCommandBuffer; -import org.lwjgl.vulkan.VkRect2D; -import org.lwjgl.vulkan.VkViewport; + +import java.lang.foreign.Arena; import static org.lwjgl.vulkan.KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; import static org.lwjgl.vulkan.VK10.*; public class DefaultMainPass implements MainPass { - public static DefaultMainPass create() { - return new DefaultMainPass(); - } - - private RenderTarget mainTarget; private final Framebuffer mainFramebuffer; - + private RenderTarget mainTarget; private RenderPass mainRenderPass; private RenderPass auxRenderPass; - private VkGlTexture[] colorAttachmentTextures; DefaultMainPass() { @@ -39,6 +32,10 @@ public static DefaultMainPass create() { createSwapChainTextures(); } + public static DefaultMainPass create() { + return new DefaultMainPass(); + } + private void createRenderPasses() { RenderPass.Builder builder = RenderPass.builder(this.mainFramebuffer); builder.getColorAttachmentInfo().setFinalLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); @@ -57,28 +54,26 @@ private void createRenderPasses() { } @Override - public void begin(VkCommandBuffer commandBuffer, MemoryStack stack) { + public void begin(VkCommandBuffer commandBuffer) { SwapChain framebuffer = Renderer.getInstance().getSwapChain(); - VulkanImage colorAttachment = framebuffer.getColorAttachment(); - colorAttachment.transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - - framebuffer.beginRenderPass(commandBuffer, this.mainRenderPass, stack); - - VkViewport.Buffer pViewport = framebuffer.viewport(stack); - vkCmdSetViewport(commandBuffer, 0, pViewport); + try (Arena arena = Arena.ofConfined()) { + VulkanImage colorAttachment = framebuffer.getColorAttachment(); + VulkanImage.transitionImageLayout(arena, commandBuffer, colorAttachment, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + } - VkRect2D.Buffer pScissor = framebuffer.scissor(stack); - vkCmdSetScissor(commandBuffer, 0, pScissor); + framebuffer.beginRenderPass(commandBuffer, this.mainRenderPass); + framebuffer.applyViewport(commandBuffer); + framebuffer.applyScissor(commandBuffer); } @Override public void end(VkCommandBuffer commandBuffer) { Renderer.getInstance().endRenderPass(commandBuffer); - try (MemoryStack stack = MemoryStack.stackPush()) { + try (Arena arena = Arena.ofConfined()) { SwapChain framebuffer = Renderer.getInstance().getSwapChain(); - framebuffer.getColorAttachment().transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); + VulkanImage.transitionImageLayout(arena, commandBuffer, framebuffer.getColorAttachment(), VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); } int result = vkEndCommandBuffer(commandBuffer); @@ -109,10 +104,7 @@ public void rebindMainTarget() { Renderer.getInstance().endRenderPass(commandBuffer); - try (MemoryStack stack = MemoryStack.stackPush()) { - swapChain.beginRenderPass(commandBuffer, this.auxRenderPass, stack); - } - + swapChain.beginRenderPass(commandBuffer, this.auxRenderPass); } @Override @@ -125,8 +117,8 @@ public void bindAsTexture() { if (boundRenderPass == this.mainRenderPass || boundRenderPass == this.auxRenderPass) Renderer.getInstance().endRenderPass(commandBuffer); - try (MemoryStack stack = MemoryStack.stackPush()) { - swapChain.getColorAttachment().transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + try (Arena arena = Arena.ofConfined()) { + VulkanImage.transitionImageLayout(arena, commandBuffer, swapChain.getColorAttachment(), VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); } VTextureSelector.bindTexture(swapChain.getColorAttachment()); diff --git a/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java b/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java index 7ce219748..aeb28a538 100644 --- a/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java +++ b/src/main/java/net/vulkanmod/vulkan/pass/MainPass.java @@ -1,12 +1,11 @@ package net.vulkanmod.vulkan.pass; import net.vulkanmod.gl.VkGlTexture; -import org.lwjgl.system.MemoryStack; import org.lwjgl.vulkan.VkCommandBuffer; public interface MainPass { - void begin(VkCommandBuffer commandBuffer, MemoryStack stack); + void begin(VkCommandBuffer commandBuffer); void end(VkCommandBuffer commandBuffer); @@ -14,13 +13,17 @@ public interface MainPass { void onResize(); - default void mainTargetBindWrite() {} + default void mainTargetBindWrite() { + } - default void mainTargetUnbindWrite() {} + default void mainTargetUnbindWrite() { + } - default void rebindMainTarget() {} + default void rebindMainTarget() { + } - default void bindAsTexture() {} + default void bindAsTexture() { + } default VkGlTexture getColorAttachment() { throw new UnsupportedOperationException(); diff --git a/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java b/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java index d6de2982e..70ae58396 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/CommandPool.java @@ -14,10 +14,9 @@ import static org.lwjgl.vulkan.VK10.*; public class CommandPool { - long id; - private final List commandBuffers = new ObjectArrayList<>(); private final java.util.Queue availableCmdBuffers = new ArrayDeque<>(); + long id; CommandPool(int queueFamilyIndex) { this.createCommandPool(queueFamilyIndex); diff --git a/src/main/java/net/vulkanmod/vulkan/queue/GraphicsQueue.java b/src/main/java/net/vulkanmod/vulkan/queue/GraphicsQueue.java index e449f617b..f7f25a411 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/GraphicsQueue.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/GraphicsQueue.java @@ -1,13 +1,9 @@ package net.vulkanmod.vulkan.queue; import net.vulkanmod.vulkan.Synchronization; -import net.vulkanmod.vulkan.Vulkan; -import net.vulkanmod.vulkan.memory.MemoryManager; -import net.vulkanmod.vulkan.util.VUtil; import org.lwjgl.system.MemoryStack; -import org.lwjgl.vulkan.*; -import static org.lwjgl.vulkan.VK10.*; +import static org.lwjgl.vulkan.VK10.VK_NULL_HANDLE; public class GraphicsQueue extends Queue { public static GraphicsQueue INSTANCE; diff --git a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java index c6bb61182..f548b7c27 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/Queue.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/Queue.java @@ -25,15 +25,6 @@ public abstract class Queue { protected CommandPool commandPool; - public synchronized CommandPool.CommandBuffer beginCommands() { - try (MemoryStack stack = stackPush()) { - CommandPool.CommandBuffer commandBuffer = this.commandPool.getCommandBuffer(stack); - commandBuffer.begin(stack); - - return commandBuffer; - } - } - Queue(MemoryStack stack, int familyIndex) { this(stack, familyIndex, true); } @@ -47,35 +38,6 @@ public synchronized CommandPool.CommandBuffer beginCommands() { this.commandPool = new CommandPool(familyIndex); } - public synchronized long submitCommands(CommandPool.CommandBuffer commandBuffer) { - try (MemoryStack stack = stackPush()) { - return commandBuffer.submitCommands(stack, queue, false); - } - } - - public VkQueue queue() { - return this.queue; - } - - public void cleanUp() { - if (commandPool != null) - commandPool.cleanUp(); - } - - public void waitIdle() { - vkQueueWaitIdle(queue); - } - - public CommandPool getCommandPool() { - return commandPool; - } - - public enum Family { - Graphics, - Transfer, - Compute - } - public static QueueFamilyIndices getQueueFamilies() { if (device == null) device = Vulkan.getVkDevice(); @@ -191,6 +153,44 @@ public static QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device) { } } + public synchronized CommandPool.CommandBuffer beginCommands() { + try (MemoryStack stack = stackPush()) { + CommandPool.CommandBuffer commandBuffer = this.commandPool.getCommandBuffer(stack); + commandBuffer.begin(stack); + + return commandBuffer; + } + } + + public synchronized long submitCommands(CommandPool.CommandBuffer commandBuffer) { + try (MemoryStack stack = stackPush()) { + return commandBuffer.submitCommands(stack, queue, false); + } + } + + public VkQueue queue() { + return this.queue; + } + + public void cleanUp() { + if (commandPool != null) + commandPool.cleanUp(); + } + + public void waitIdle() { + vkQueueWaitIdle(queue); + } + + public CommandPool getCommandPool() { + return commandPool; + } + + public enum Family { + Graphics, + Transfer, + Compute + } + public static class QueueFamilyIndices { public int graphicsFamily = VK_QUEUE_FAMILY_IGNORED; public int presentFamily = VK_QUEUE_FAMILY_IGNORED; diff --git a/src/main/java/net/vulkanmod/vulkan/queue/TransferQueue.java b/src/main/java/net/vulkanmod/vulkan/queue/TransferQueue.java index 4cd17c4d6..7f83744f2 100644 --- a/src/main/java/net/vulkanmod/vulkan/queue/TransferQueue.java +++ b/src/main/java/net/vulkanmod/vulkan/queue/TransferQueue.java @@ -19,6 +19,19 @@ public TransferQueue(MemoryStack stack, int familyIndex) { super(stack, familyIndex); } + public static void uploadBufferCmd(VkCommandBuffer commandBuffer, long srcBuffer, long srcOffset, long dstBuffer, long dstOffset, long size) { + + try (MemoryStack stack = stackPush()) { + + VkBufferCopy.Buffer copyRegion = VkBufferCopy.calloc(1, stack); + copyRegion.size(size); + copyRegion.srcOffset(srcOffset); + copyRegion.dstOffset(dstOffset); + + vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, copyRegion); + } + } + public long copyBufferCmd(long srcBuffer, long srcOffset, long dstBuffer, long dstOffset, long size) { try (MemoryStack stack = stackPush()) { @@ -57,17 +70,4 @@ public void uploadBufferImmediate(long srcBuffer, long srcOffset, long dstBuffer } } - public static void uploadBufferCmd(VkCommandBuffer commandBuffer, long srcBuffer, long srcOffset, long dstBuffer, long dstOffset, long size) { - - try (MemoryStack stack = stackPush()) { - - VkBufferCopy.Buffer copyRegion = VkBufferCopy.calloc(1, stack); - copyRegion.size(size); - copyRegion.srcOffset(srcOffset); - copyRegion.dstOffset(dstOffset); - - vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, copyRegion); - } - } - } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java index d94ad1b02..422bd82bd 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/GraphicsPipeline.java @@ -16,7 +16,6 @@ import java.nio.LongBuffer; import java.util.List; -import static org.lwjgl.system.MemoryStack.stackGet; import static org.lwjgl.system.MemoryStack.stackPush; import static org.lwjgl.vulkan.VK10.*; @@ -44,16 +43,147 @@ public class GraphicsPipeline extends Pipeline { createShaderModules(builder.vertShaderSPIRV, builder.fragShaderSPIRV); if (builder.renderPass != null) - graphicsPipelines.computeIfAbsent(PipelineState.DEFAULT, - this::createGraphicsPipeline); + graphicsPipelines.computeLongIfAbsent(PipelineState.DEFAULT, this::createGraphicsPipeline); createDescriptorSets(Renderer.getFramesNum()); PIPELINES.add(this); } + private static VkVertexInputBindingDescription.Buffer getBindingDescription(VertexFormat vertexFormat) { + VkVertexInputBindingDescription.Buffer bindingDescription = VkVertexInputBindingDescription.calloc(1); + + bindingDescription.binding(0); + bindingDescription.stride(vertexFormat.getVertexSize()); + bindingDescription.inputRate(VK_VERTEX_INPUT_RATE_VERTEX); + + return bindingDescription; + } + + private static VkVertexInputAttributeDescription.Buffer getAttributeDescriptions(VertexFormat vertexFormat) { + List elements = vertexFormat.getElements(); + + int size = elements.size(); + + VkVertexInputAttributeDescription.Buffer attributeDescriptions = VkVertexInputAttributeDescription.calloc(size); + + int offset = 0; + + for (int i = 0; i < size; ++i) { + VkVertexInputAttributeDescription posDescription = attributeDescriptions.get(i); + posDescription.binding(0); + posDescription.location(i); + + VertexFormatElement formatElement = elements.get(i); + VertexFormatElement.Usage usage = formatElement.usage(); + VertexFormatElement.Type type = formatElement.type(); + int elementCount = formatElement.count(); + + switch (usage) { + case POSITION -> { + switch (type) { + case FLOAT -> { + posDescription.format(VK_FORMAT_R32G32B32_SFLOAT); + posDescription.offset(offset); + + offset += 12; + } + case SHORT -> { + posDescription.format(VK_FORMAT_R16G16B16A16_SINT); + posDescription.offset(offset); + + offset += 8; + } + case BYTE -> { + posDescription.format(VK_FORMAT_R8G8B8A8_SINT); + posDescription.offset(offset); + + offset += 4; + } + } + + } + + case COLOR -> { + switch (type) { + case UBYTE -> { + posDescription.format(VK_FORMAT_R8G8B8A8_UNORM); + posDescription.offset(offset); + + offset += 4; + } + case UINT -> { + posDescription.format(VK_FORMAT_R32_UINT); + posDescription.offset(offset); + + offset += 4; + } + } + } + + case UV -> { + switch (type) { + case FLOAT -> { + posDescription.format(VK_FORMAT_R32G32_SFLOAT); + posDescription.offset(offset); + + offset += 8; + } + case SHORT -> { + posDescription.format(VK_FORMAT_R16G16_SINT); + posDescription.offset(offset); + + offset += 4; + } + case USHORT -> { + posDescription.format(VK_FORMAT_R16G16_UINT); + posDescription.offset(offset); + + offset += 4; + } + case UINT -> { + posDescription.format(VK_FORMAT_R32_UINT); + posDescription.offset(offset); + + offset += 4; + } + } + } + + case NORMAL -> { + posDescription.format(VK_FORMAT_R8G8B8A8_SNORM); + posDescription.offset(offset); + + offset += 4; + } + + case GENERIC -> { + if (type == VertexFormatElement.Type.SHORT && elementCount == 1) { + posDescription.format(VK_FORMAT_R16_SINT); + posDescription.offset(offset); + + offset += 2; + } else if (type == VertexFormatElement.Type.INT && elementCount == 1) { + posDescription.format(VK_FORMAT_R32_SINT); + posDescription.offset(offset); + + offset += 4; + } else { + throw new RuntimeException(String.format("Unknown format: %s", usage)); + } + } + + default -> throw new RuntimeException(String.format("Unknown format: %s", usage)); + } + + posDescription.offset(((VertexFormatMixed) (vertexFormat)).getOffset(i)); + } + + return attributeDescriptions.rewind(); + } + public long getHandle(PipelineState state) { - return graphicsPipelines.computeIfAbsent(state, this::createGraphicsPipeline); + return graphicsPipelines.computeLongIfAbsent(state, this::createGraphicsPipeline); } private long createGraphicsPipeline(PipelineState state) { @@ -147,8 +277,7 @@ private long createGraphicsPipeline(PipelineState state) { colorBlendAttachment.srcAlphaBlendFactor(PipelineState.BlendState.getSrcAlphaFactor(state.blendState_i)); colorBlendAttachment.dstAlphaBlendFactor(PipelineState.BlendState.getDstAlphaFactor(state.blendState_i)); colorBlendAttachment.alphaBlendOp(PipelineState.BlendState.blendOp(state.blendState_i)); - } - else { + } else { colorBlendAttachment.blendEnable(false); } @@ -165,13 +294,9 @@ private long createGraphicsPipeline(PipelineState state) { dynamicStates.sType(VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO); if (topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || polygonMode == VK_POLYGON_MODE_LINE) { - dynamicStates.pDynamicStates( - stack.ints(VK_DYNAMIC_STATE_DEPTH_BIAS, VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, - VK_DYNAMIC_STATE_LINE_WIDTH)); - } - else { - dynamicStates.pDynamicStates( - stack.ints(VK_DYNAMIC_STATE_DEPTH_BIAS, VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR)); + dynamicStates.pDynamicStates(stack.ints(VK_DYNAMIC_STATE_DEPTH_BIAS, VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_LINE_WIDTH)); + } else { + dynamicStates.pDynamicStates(stack.ints(VK_DYNAMIC_STATE_DEPTH_BIAS, VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR)); } VkGraphicsPipelineCreateInfo.Buffer pipelineInfo = VkGraphicsPipelineCreateInfo.calloc(1, stack); @@ -192,8 +317,7 @@ private long createGraphicsPipeline(PipelineState state) { if (!Vulkan.DYNAMIC_RENDERING) { pipelineInfo.renderPass(state.renderPass.getId()); pipelineInfo.subpass(0); - } - else { + } else { //dyn-rendering VkPipelineRenderingCreateInfoKHR renderingInfo = VkPipelineRenderingCreateInfoKHR.calloc(stack); renderingInfo.sType(KHRDynamicRendering.VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR); @@ -204,8 +328,7 @@ private long createGraphicsPipeline(PipelineState state) { LongBuffer pGraphicsPipeline = stack.mallocLong(1); - Vulkan.checkResult(vkCreateGraphicsPipelines(DeviceManager.vkDevice, PIPELINE_CACHE, pipelineInfo, null, pGraphicsPipeline), - "Failed to create graphics pipeline " + this.name); + Vulkan.checkResult(vkCreateGraphicsPipelines(DeviceManager.vkDevice, PIPELINE_CACHE, pipelineInfo, null, pGraphicsPipeline), "Failed to create graphics pipeline " + this.name); return pGraphicsPipeline.get(0); } @@ -250,138 +373,4 @@ void cleanUp() { MemoryUtil.memFree(this.attributeDescriptions); } } - - private static VkVertexInputBindingDescription.Buffer getBindingDescription(VertexFormat vertexFormat) { - VkVertexInputBindingDescription.Buffer bindingDescription = VkVertexInputBindingDescription.calloc(1); - - bindingDescription.binding(0); - bindingDescription.stride(vertexFormat.getVertexSize()); - bindingDescription.inputRate(VK_VERTEX_INPUT_RATE_VERTEX); - - return bindingDescription; - } - - private static VkVertexInputAttributeDescription.Buffer getAttributeDescriptions(VertexFormat vertexFormat) { - List elements = vertexFormat.getElements(); - - int size = elements.size(); - - VkVertexInputAttributeDescription.Buffer attributeDescriptions = VkVertexInputAttributeDescription.calloc(size); - - int offset = 0; - - for (int i = 0; i < size; ++i) { - VkVertexInputAttributeDescription posDescription = attributeDescriptions.get(i); - posDescription.binding(0); - posDescription.location(i); - - VertexFormatElement formatElement = elements.get(i); - VertexFormatElement.Usage usage = formatElement.usage(); - VertexFormatElement.Type type = formatElement.type(); - int elementCount = formatElement.count(); - - switch (usage) { - case POSITION -> { - switch (type) { - case FLOAT -> { - posDescription.format(VK_FORMAT_R32G32B32_SFLOAT); - posDescription.offset(offset); - - offset += 12; - } - case SHORT -> { - posDescription.format(VK_FORMAT_R16G16B16A16_SINT); - posDescription.offset(offset); - - offset += 8; - } - case BYTE -> { - posDescription.format(VK_FORMAT_R8G8B8A8_SINT); - posDescription.offset(offset); - - offset += 4; - } - } - - } - - case COLOR -> { - switch (type) { - case UBYTE -> { - posDescription.format(VK_FORMAT_R8G8B8A8_UNORM); - posDescription.offset(offset); - - offset += 4; - } - case UINT -> { - posDescription.format(VK_FORMAT_R32_UINT); - posDescription.offset(offset); - - offset += 4; - } - } - } - - case UV -> { - switch (type) { - case FLOAT -> { - posDescription.format(VK_FORMAT_R32G32_SFLOAT); - posDescription.offset(offset); - - offset += 8; - } - case SHORT -> { - posDescription.format(VK_FORMAT_R16G16_SINT); - posDescription.offset(offset); - - offset += 4; - } - case USHORT -> { - posDescription.format(VK_FORMAT_R16G16_UINT); - posDescription.offset(offset); - - offset += 4; - } - case UINT -> { - posDescription.format(VK_FORMAT_R32_UINT); - posDescription.offset(offset); - - offset += 4; - } - } - } - - case NORMAL -> { - posDescription.format(VK_FORMAT_R8G8B8A8_SNORM); - posDescription.offset(offset); - - offset += 4; - } - - case GENERIC -> { - if (type == VertexFormatElement.Type.SHORT && elementCount == 1) { - posDescription.format(VK_FORMAT_R16_SINT); - posDescription.offset(offset); - - offset += 2; - } - else if (type == VertexFormatElement.Type.INT && elementCount == 1) { - posDescription.format(VK_FORMAT_R32_SINT); - posDescription.offset(offset); - - offset += 4; - } - else { - throw new RuntimeException(String.format("Unknown format: %s", usage)); - } - } - - default -> throw new RuntimeException(String.format("Unknown format: %s", usage)); - } - - posDescription.offset(((VertexFormatMixed) (vertexFormat)).getOffset(i)); - } - - return attributeDescriptions.rewind(); - } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java index 49d146cf2..8bb7347a5 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/Pipeline.java @@ -42,9 +42,20 @@ public abstract class Pipeline { + protected static final List PIPELINES = new LinkedList<>(); private static final VkDevice DEVICE = Vulkan.getVkDevice(); protected static final long PIPELINE_CACHE = createPipelineCache(); - protected static final List PIPELINES = new LinkedList<>(); + public final String name; + protected long descriptorSetLayout; + protected long pipelineLayout; + protected DescriptorSets[] descriptorSets; + protected List buffers; + protected ManualUBO manualUBO; + protected List imageDescriptors; + protected PushConstants pushConstants; + public Pipeline(String name) { + this.name = name; + } private static long createPipelineCache() { try (MemoryStack stack = stackPush()) { @@ -73,19 +84,23 @@ public static void recreateDescriptorSets(int frames) { }); } - public final String name; + static long createShaderModule(ByteBuffer spirvCode) { - protected long descriptorSetLayout; - protected long pipelineLayout; + try (MemoryStack stack = stackPush()) { - protected DescriptorSets[] descriptorSets; - protected List buffers; - protected ManualUBO manualUBO; - protected List imageDescriptors; - protected PushConstants pushConstants; + VkShaderModuleCreateInfo createInfo = VkShaderModuleCreateInfo.calloc(stack); - public Pipeline(String name) { - this.name = name; + createInfo.sType(VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO); + createInfo.pCode(spirvCode); + + LongBuffer pShaderModule = stack.mallocLong(1); + + if (vkCreateShaderModule(DEVICE, createInfo, null, pShaderModule) != VK_SUCCESS) { + throw new RuntimeException("Failed to create shader module"); + } + + return pShaderModule.get(0); + } } protected void createDescriptorSetLayout() { @@ -179,8 +194,7 @@ public ManualUBO getManualUBO() { } public void resetDescriptorPool(int i) { - if (this.descriptorSets != null) - this.descriptorSets[i].resetIdx(); + if (this.descriptorSets != null) this.descriptorSets[i].resetIdx(); } @@ -205,37 +219,17 @@ public void bindDescriptorSets(VkCommandBuffer commandBuffer, UniformBuffer unif this.descriptorSets[frame].bindSets(commandBuffer, uniformBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS); } - static long createShaderModule(ByteBuffer spirvCode) { - - try (MemoryStack stack = stackPush()) { - - VkShaderModuleCreateInfo createInfo = VkShaderModuleCreateInfo.calloc(stack); - - createInfo.sType(VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO); - createInfo.pCode(spirvCode); - - LongBuffer pShaderModule = stack.mallocLong(1); - - if (vkCreateShaderModule(DEVICE, createInfo, null, pShaderModule) != VK_SUCCESS) { - throw new RuntimeException("Failed to create shader module"); - } - - return pShaderModule.get(0); - } - } - protected static class DescriptorSets { private final Pipeline pipeline; + private final long[] boundUBs; + private final ImageDescriptor.State[] boundTextures; + private final IntBuffer dynamicOffsets; private int poolSize = 10; private long descriptorPool; private LongBuffer sets; private long currentSet; private int currentIdx = -1; - private final long[] boundUBs; - private final ImageDescriptor.State[] boundTextures; - private final IntBuffer dynamicOffsets; - DescriptorSets(Pipeline pipeline) { this.pipeline = pipeline; this.boundTextures = new ImageDescriptor.State[pipeline.imageDescriptors.size()]; @@ -256,8 +250,7 @@ protected void bindSets(VkCommandBuffer commandBuffer, UniformBuffer uniformBuff this.updateUniforms(uniformBuffer); this.updateDescriptorSet(stack, uniformBuffer); - vkCmdBindDescriptorSets(commandBuffer, bindPoint, pipeline.pipelineLayout, - 0, stack.longs(currentSet), dynamicOffsets); + vkCmdBindDescriptorSets(commandBuffer, bindPoint, pipeline.pipelineLayout, 0, stack.longs(currentSet), dynamicOffsets); } } @@ -285,8 +278,7 @@ private void updateUniforms(UniformBuffer globalUB) { } private boolean needsUpdate(UniformBuffer uniformBuffer) { - if (currentIdx == -1) - return true; + if (currentIdx == -1) return true; for (int j = 0; j < pipeline.imageDescriptors.size(); ++j) { ImageDescriptor imageDescriptor = pipeline.imageDescriptors.get(j); @@ -294,8 +286,7 @@ private boolean needsUpdate(UniformBuffer uniformBuffer) { long view = imageDescriptor.getImageView(image); long sampler = image.getSampler(); - if (imageDescriptor.isReadOnlyLayout) - image.readOnlyLayout(); + if (imageDescriptor.isReadOnlyLayout) image.readOnlyLayout(); if (!this.boundTextures[j].isCurrentState(view, sampler)) { return true; @@ -306,8 +297,7 @@ private boolean needsUpdate(UniformBuffer uniformBuffer) { UBO ubo = pipeline.buffers.get(j); UniformBuffer uniformBufferI = ubo.getUniformBuffer(); - if (uniformBufferI == null) - uniformBufferI = uniformBuffer; + if (uniformBufferI == null) uniformBufferI = uniformBuffer; if (this.boundUBs[j] != uniformBufferI.getId()) { return true; @@ -333,8 +323,7 @@ private void checkPoolSize(MemoryStack stack) { private void updateDescriptorSet(MemoryStack stack, UniformBuffer uniformBuffer) { //Check if update is needed - if (!needsUpdate(uniformBuffer)) - return; + if (!needsUpdate(uniformBuffer)) return; this.currentIdx++; @@ -350,8 +339,7 @@ private void updateDescriptorSet(MemoryStack stack, UniformBuffer uniformBuffer) int i = 0; for (UBO ubo : pipeline.buffers) { UniformBuffer ub = ubo.getUniformBuffer(); - if (ub == null) - ub = uniformBuffer; + if (ub == null) ub = uniformBuffer; boundUBs[i] = ub.getId(); bufferInfos[i] = VkDescriptorBufferInfo.calloc(1, stack); @@ -379,15 +367,13 @@ private void updateDescriptorSet(MemoryStack stack, UniformBuffer uniformBuffer) long sampler = image.getSampler(); int layout = imageDescriptor.getLayout(); - if (imageDescriptor.isReadOnlyLayout) - image.readOnlyLayout(); + if (imageDescriptor.isReadOnlyLayout) image.readOnlyLayout(); imageInfo[j] = VkDescriptorImageInfo.calloc(1, stack); imageInfo[j].imageLayout(layout); imageInfo[j].imageView(view); - if (imageDescriptor.useSampler) - imageInfo[j].sampler(sampler); + if (imageDescriptor.useSampler) imageInfo[j].sampler(sampler); VkWriteDescriptorSet samplerDescriptorWrite = descriptorWrites.get(i); samplerDescriptorWrite.sType(VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET); @@ -508,13 +494,21 @@ public Builder() { this(null, null); } + public static int getStageFromString(String s) { + return switch (s) { + case "vertex" -> VK_SHADER_STAGE_VERTEX_BIT; + case "fragment" -> VK_SHADER_STAGE_FRAGMENT_BIT; + case "all" -> VK_SHADER_STAGE_ALL_GRAPHICS; + case "compute" -> VK_SHADER_STAGE_COMPUTE_BIT; + + default -> throw new RuntimeException("cannot identify type.."); + }; + } + public GraphicsPipeline createGraphicsPipeline() { - Validate.isTrue(this.imageDescriptors != null && this.UBOs != null - && this.vertShaderSPIRV != null && this.fragShaderSPIRV != null, - "Cannot create Pipeline: resources missing"); + Validate.isTrue(this.imageDescriptors != null && this.UBOs != null && this.vertShaderSPIRV != null && this.fragShaderSPIRV != null, "Cannot create Pipeline: resources missing"); - if (this.manualUBO != null) - this.UBOs.add(this.manualUBO); + if (this.manualUBO != null) this.UBOs.add(this.manualUBO); return new GraphicsPipeline(this); } @@ -603,8 +597,7 @@ private void parseUboNode(JsonElement jsonelement) { } uniformInfo.setBufferSupplier(uniformSupplier); - } - else { + } else { throw new IllegalStateException("No uniform supplier found for uniform: (%s:%s)".formatted(type2, name)); } } @@ -614,8 +607,7 @@ private void parseUboNode(JsonElement jsonelement) { UBO ubo = builder.buildUBO(binding, type); - if (binding >= this.nextBinding) - this.nextBinding = binding + 1; + if (binding >= this.nextBinding) this.nextBinding = binding + 1; this.UBOs.add(ubo); } @@ -626,8 +618,7 @@ private void parseManualUboNode(JsonElement jsonelement) { int stage = getStageFromString(GsonHelper.getAsString(jsonobject, "type")); int size = GsonHelper.getAsInt(jsonobject, "size"); - if (binding >= this.nextBinding) - this.nextBinding = binding + 1; + if (binding >= this.nextBinding) this.nextBinding = binding + 1; this.manualUBO = new ManualUBO(binding, stage, size); } @@ -659,16 +650,5 @@ private void parsePushConstantNode(JsonArray jsonArray) { this.pushConstants = builder.buildPushConstant(); } - - public static int getStageFromString(String s) { - return switch (s) { - case "vertex" -> VK_SHADER_STAGE_VERTEX_BIT; - case "fragment" -> VK_SHADER_STAGE_FRAGMENT_BIT; - case "all" -> VK_SHADER_STAGE_ALL_GRAPHICS; - case "compute" -> VK_SHADER_STAGE_COMPUTE_BIT; - - default -> throw new RuntimeException("cannot identify type.."); - }; - } } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/PipelineState.java b/src/main/java/net/vulkanmod/vulkan/shader/PipelineState.java index 8015cbf1b..cc651410e 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/PipelineState.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/PipelineState.java @@ -1,6 +1,8 @@ package net.vulkanmod.vulkan.shader; -import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.opengl.GlConst; +import com.mojang.blaze3d.platform.DestFactor; +import com.mojang.blaze3d.platform.SourceFactor; import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.framebuffer.RenderPass; @@ -17,6 +19,22 @@ public class PipelineState { public static final PipelineState DEFAULT = new PipelineState(getAssemblyRasterState(), getBlendState(), getDepthState(), getLogicOpState(), VRenderSystem.getColorMask(), null); public static PipelineState currentState = DEFAULT; + final RenderPass renderPass; + int assemblyRasterState; + int blendState_i; + int depthState_i; + int colorMask_i; + int logicOp_i; + + public PipelineState(int assemblyRasterState, int blendState, int depthState, int logicOp, int colorMask, RenderPass renderPass) { + this.renderPass = renderPass; + + this.assemblyRasterState = assemblyRasterState; + this.blendState_i = blendState; + this.depthState_i = depthState; + this.colorMask_i = colorMask; + this.logicOp_i = logicOp; + } public static PipelineState getCurrentPipelineState(RenderPass renderPass) { int assemblyRasterState = getAssemblyRasterState(); @@ -60,45 +78,21 @@ public static int getLogicOpState() { return logicOpState; } - final RenderPass renderPass; - - int assemblyRasterState; - int blendState_i; - int depthState_i; - int colorMask_i; - int logicOp_i; - - public PipelineState(int assemblyRasterState, int blendState, int depthState, int logicOp, int colorMask, - RenderPass renderPass) { - this.renderPass = renderPass; - - this.assemblyRasterState = assemblyRasterState; - this.blendState_i = blendState; - this.depthState_i = depthState; - this.colorMask_i = colorMask; - this.logicOp_i = logicOp; + public static BlendInfo defaultBlendInfo() { + return new BlendInfo(true, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD); } - private boolean checkEquals(int assemblyRasterState, int blendState, int depthState, int logicOp, int colorMask, - RenderPass renderPass) { - return (blendState == this.blendState_i) && (depthState == this.depthState_i) - && renderPass == this.renderPass && logicOp == this.logicOp_i - && (assemblyRasterState == this.assemblyRasterState) - && colorMask == this.colorMask_i; + private boolean checkEquals(int assemblyRasterState, int blendState, int depthState, int logicOp, int colorMask, RenderPass renderPass) { + return (blendState == this.blendState_i) && (depthState == this.depthState_i) && renderPass == this.renderPass && logicOp == this.logicOp_i && (assemblyRasterState == this.assemblyRasterState) && colorMask == this.colorMask_i; } @Override public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; PipelineState that = (PipelineState) o; - return (blendState_i == that.blendState_i) && (depthState_i == that.depthState_i) - && this.renderPass == that.renderPass && logicOp_i == that.logicOp_i - && this.assemblyRasterState == that.assemblyRasterState - && this.colorMask_i == that.colorMask_i; + return (blendState_i == that.blendState_i) && (depthState_i == that.depthState_i) && this.renderPass == that.renderPass && logicOp_i == that.logicOp_i && this.assemblyRasterState == that.assemblyRasterState && this.colorMask_i == that.colorMask_i; } @Override @@ -106,11 +100,6 @@ public int hashCode() { return Objects.hash(blendState_i, depthState_i, logicOp_i, assemblyRasterState, colorMask_i, renderPass); } - public static BlendInfo defaultBlendInfo() { - return new BlendInfo(true, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, - VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD); - } - public static class BlendInfo { public boolean enabled; public int srcRgbFactor; @@ -119,8 +108,7 @@ public static class BlendInfo { public int dstAlphaFactor; public int blendOp; - public BlendInfo(boolean enabled, int srcRgbFactor, int dstRgbFactor, int srcAlphaFactor, int dstAlphaFactor, - int blendOp) { + public BlendInfo(boolean enabled, int srcRgbFactor, int dstRgbFactor, int srcAlphaFactor, int dstAlphaFactor, int blendOp) { this.enabled = enabled; this.srcRgbFactor = srcRgbFactor; this.dstRgbFactor = dstRgbFactor; @@ -129,46 +117,6 @@ public BlendInfo(boolean enabled, int srcRgbFactor, int dstRgbFactor, int srcAlp this.blendOp = blendOp; } - public void setBlendFunction(GlStateManager.SourceFactor sourceFactor, GlStateManager.DestFactor destFactor) { - this.srcRgbFactor = glToVulkanBlendFactor(sourceFactor.value); - this.srcAlphaFactor = glToVulkanBlendFactor(sourceFactor.value); - this.dstRgbFactor = glToVulkanBlendFactor(destFactor.value); - this.dstAlphaFactor = glToVulkanBlendFactor(destFactor.value); - } - - public void setBlendFuncSeparate(GlStateManager.SourceFactor srcRgb, GlStateManager.DestFactor dstRgb, - GlStateManager.SourceFactor srcAlpha, GlStateManager.DestFactor dstAlpha) { - this.srcRgbFactor = glToVulkanBlendFactor(srcRgb.value); - this.srcAlphaFactor = glToVulkanBlendFactor(srcAlpha.value); - this.dstRgbFactor = glToVulkanBlendFactor(dstRgb.value); - this.dstAlphaFactor = glToVulkanBlendFactor(dstAlpha.value); - } - - /* gl to Vulkan conversion */ - public void setBlendFunction(int sourceFactor, int destFactor) { - this.srcRgbFactor = glToVulkanBlendFactor(sourceFactor); - this.srcAlphaFactor = glToVulkanBlendFactor(sourceFactor); - this.dstRgbFactor = glToVulkanBlendFactor(destFactor); - this.dstAlphaFactor = glToVulkanBlendFactor(destFactor); - } - - /* gl to Vulkan conversion */ - public void setBlendFuncSeparate(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { - this.srcRgbFactor = glToVulkanBlendFactor(srcRgb); - this.srcAlphaFactor = glToVulkanBlendFactor(srcAlpha); - this.dstRgbFactor = glToVulkanBlendFactor(dstRgb); - this.dstAlphaFactor = glToVulkanBlendFactor(dstAlpha); - } - - public void setBlendOp(int i) { - this.blendOp = glToVulkanBlendOp(i); - } - - - public int createBlendState() { - return BlendState.getState(this); - } - private static int glToVulkanBlendOp(int value) { return switch (value) { case 0x8006 -> VK_BLEND_OP_ADD; @@ -217,6 +165,46 @@ private static int glToVulkanBlendFactor(int value) { // ZERO(0); }; } + + public void setBlendFunction(SourceFactor sourceFactor, DestFactor destFactor) { + int src = GlConst.toGl(sourceFactor); + int dst = GlConst.toGl(destFactor); + this.srcRgbFactor = glToVulkanBlendFactor(src); + this.srcAlphaFactor = glToVulkanBlendFactor(src); + this.dstRgbFactor = glToVulkanBlendFactor(dst); + this.dstAlphaFactor = glToVulkanBlendFactor(dst); + } + + public void setBlendFuncSeparate(SourceFactor srcRgb, DestFactor dstRgb, SourceFactor srcAlpha, DestFactor dstAlpha) { + this.srcRgbFactor = glToVulkanBlendFactor(GlConst.toGl(srcRgb)); + this.srcAlphaFactor = glToVulkanBlendFactor(GlConst.toGl(srcAlpha)); + this.dstRgbFactor = glToVulkanBlendFactor(GlConst.toGl(dstRgb)); + this.dstAlphaFactor = glToVulkanBlendFactor(GlConst.toGl(dstAlpha)); + } + + /* gl to Vulkan conversion */ + public void setBlendFunction(int sourceFactor, int destFactor) { + this.srcRgbFactor = glToVulkanBlendFactor(sourceFactor); + this.srcAlphaFactor = glToVulkanBlendFactor(sourceFactor); + this.dstRgbFactor = glToVulkanBlendFactor(destFactor); + this.dstAlphaFactor = glToVulkanBlendFactor(destFactor); + } + + /* gl to Vulkan conversion */ + public void setBlendFuncSeparate(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { + this.srcRgbFactor = glToVulkanBlendFactor(srcRgb); + this.srcAlphaFactor = glToVulkanBlendFactor(srcAlpha); + this.dstRgbFactor = glToVulkanBlendFactor(dstRgb); + this.dstAlphaFactor = glToVulkanBlendFactor(dstAlpha); + } + + public void setBlendOp(int i) { + this.blendOp = glToVulkanBlendOp(i); + } + + public int createBlendState() { + return BlendState.getState(this); + } } public static class BlendState { @@ -342,10 +330,7 @@ public static int decodeCullMode(int state) { public static abstract class ColorMask { public static int getColorMask(boolean r, boolean g, boolean b, boolean a) { - return (r ? VK_COLOR_COMPONENT_R_BIT : 0) - | (g ? VK_COLOR_COMPONENT_G_BIT : 0) - | (b ? VK_COLOR_COMPONENT_B_BIT : 0) - | (a ? VK_COLOR_COMPONENT_A_BIT : 0); + return (r ? VK_COLOR_COMPONENT_R_BIT : 0) | (g ? VK_COLOR_COMPONENT_G_BIT : 0) | (b ? VK_COLOR_COMPONENT_B_BIT : 0) | (a ? VK_COLOR_COMPONENT_A_BIT : 0); } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/RayTracingPipeline.java b/src/main/java/net/vulkanmod/vulkan/shader/RayTracingPipeline.java new file mode 100644 index 000000000..212ea901f --- /dev/null +++ b/src/main/java/net/vulkanmod/vulkan/shader/RayTracingPipeline.java @@ -0,0 +1,229 @@ +package net.vulkanmod.vulkan.shader; + +import net.vulkanmod.vulkan.device.DeviceManager; +import net.vulkanmod.vulkan.memory.MemoryTypes; +import net.vulkanmod.vulkan.memory.buffer.Buffer; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.vulkan.*; + +import java.nio.ByteBuffer; +import java.nio.LongBuffer; + +import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.vulkan.KHRRayTracingPipeline.*; +import static org.lwjgl.vulkan.VK10.*; +import static org.lwjgl.vulkan.VK11.vkGetPhysicalDeviceProperties2; +import static org.lwjgl.vulkan.VK12.VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; +import static org.lwjgl.vulkan.VK12.vkGetBufferDeviceAddress; + +public class RayTracingPipeline extends Pipeline { + + private static final int VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR = 0x00000400; + + private long pipelineHandle; + + private long raygenShaderModule = 0; + private long missShaderModule = 0; + private long chitShaderModule = 0; + + private Buffer shaderBindingTable; + private long sbtBufferAddress; + private int sbtStride; + + RayTracingPipeline(Builder builder) { + super(builder.shaderPath); + this.buffers = builder.UBOs; + this.manualUBO = builder.manualUBO; + this.imageDescriptors = builder.imageDescriptors; + this.pushConstants = builder.pushConstants; + + createDescriptorSetLayout(); + createPipelineLayout(); + createShaderModules(builder.raygenShaderSPIRV, builder.missShaderSPIRV, builder.chitShaderSPIRV); + + createRayTracingPipeline(); + + createDescriptorSets(3); //Renderer.getFramesNum()); + + PIPELINES.add(this); + } + + private static int alignUp(int value, int alignment) { + long aligned = ((long) value + alignment - 1L) / alignment * alignment; + return (int) aligned; + } + + private void createShaderModules(SPIRVUtils.SPIRV raygenShaderSPIRV, SPIRVUtils.SPIRV missShaderSPIRV, SPIRVUtils.SPIRV chitShaderSPIRV) { + this.raygenShaderModule = createShaderModule(raygenShaderSPIRV.bytecode()); + this.missShaderModule = createShaderModule(missShaderSPIRV.bytecode()); + this.chitShaderModule = createShaderModule(chitShaderSPIRV.bytecode()); + } + + private void createRayTracingPipeline() { + try (MemoryStack stack = stackPush()) { + VkPipelineShaderStageCreateInfo.Buffer shaderStages = VkPipelineShaderStageCreateInfo.calloc(3, stack); + + // Ray Generation Shader + shaderStages.get(0).sType(VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO); + shaderStages.get(0).stage(VK_SHADER_STAGE_RAYGEN_BIT_KHR); + shaderStages.get(0).module(raygenShaderModule); + shaderStages.get(0).pName(stack.UTF8("main")); + + // Miss Shader + shaderStages.get(1).sType(VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO); + shaderStages.get(1).stage(VK_SHADER_STAGE_MISS_BIT_KHR); + shaderStages.get(1).module(missShaderModule); + shaderStages.get(1).pName(stack.UTF8("main")); + + // Closest Hit Shader + shaderStages.get(2).sType(VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO); + shaderStages.get(2).stage(VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR); + shaderStages.get(2).module(chitShaderModule); + shaderStages.get(2).pName(stack.UTF8("main")); + + VkRayTracingShaderGroupCreateInfoKHR.Buffer shaderGroups = VkRayTracingShaderGroupCreateInfoKHR.calloc(3, stack); + + // Ray Generation Shader Group + shaderGroups.get(0).sType(VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR); + shaderGroups.get(0).type(VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR); + shaderGroups.get(0).generalShader(0); + shaderGroups.get(0).closestHitShader(VK_SHADER_UNUSED_KHR); + shaderGroups.get(0).anyHitShader(VK_SHADER_UNUSED_KHR); + shaderGroups.get(0).intersectionShader(VK_SHADER_UNUSED_KHR); + + // Miss Shader Group + shaderGroups.get(1).sType(VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR); + shaderGroups.get(1).type(VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR); + shaderGroups.get(1).generalShader(1); + shaderGroups.get(1).closestHitShader(VK_SHADER_UNUSED_KHR); + shaderGroups.get(1).anyHitShader(VK_SHADER_UNUSED_KHR); + shaderGroups.get(1).intersectionShader(VK_SHADER_UNUSED_KHR); + + // Closest Hit Shader Group + shaderGroups.get(2).sType(VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR); + shaderGroups.get(2).type(VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR); + shaderGroups.get(2).generalShader(VK_SHADER_UNUSED_KHR); + shaderGroups.get(2).closestHitShader(2); + shaderGroups.get(2).anyHitShader(VK_SHADER_UNUSED_KHR); + shaderGroups.get(2).intersectionShader(VK_SHADER_UNUSED_KHR); + + VkRayTracingPipelineCreateInfoKHR.Buffer pipelineInfo = VkRayTracingPipelineCreateInfoKHR.calloc(1, stack); + pipelineInfo.sType(VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR); + pipelineInfo.pStages(shaderStages); + pipelineInfo.pGroups(shaderGroups); + pipelineInfo.maxPipelineRayRecursionDepth(1); + pipelineInfo.layout(pipelineLayout); + + LongBuffer pPipeline = stack.mallocLong(1); + if (vkCreateRayTracingPipelinesKHR(DeviceManager.vkDevice, VK_NULL_HANDLE, VK_NULL_HANDLE, pipelineInfo, null, pPipeline) != VK_SUCCESS) { + throw new RuntimeException("Failed to create ray tracing pipeline"); + } + pipelineHandle = pPipeline.get(0); + + createShaderBindingTable(); + } + } + + private void createShaderBindingTable() { + try (MemoryStack stack = stackPush()) { + VkPhysicalDeviceRayTracingPipelinePropertiesKHR rayTracingProperties = VkPhysicalDeviceRayTracingPipelinePropertiesKHR.calloc(stack); + rayTracingProperties.sType$Default(); + + VkPhysicalDeviceProperties2 deviceProps2 = VkPhysicalDeviceProperties2.calloc(stack); + deviceProps2.sType$Default(); + deviceProps2.pNext(rayTracingProperties.address()); + vkGetPhysicalDeviceProperties2(DeviceManager.physicalDevice, deviceProps2); + + int groupCount = 3; + int handleSize = rayTracingProperties.shaderGroupHandleSize(); + int handleAlignment = Math.max(1, rayTracingProperties.shaderGroupHandleAlignment()); + int baseAlignment = Math.max(1, rayTracingProperties.shaderGroupBaseAlignment()); + + int alignedHandleSize = alignUp(handleSize, handleAlignment); + this.sbtStride = alignUp(alignedHandleSize, baseAlignment); + int sbtSize = this.sbtStride * groupCount; + + ByteBuffer handles = MemoryUtil.memAlloc(handleSize * groupCount); + if (vkGetRayTracingShaderGroupHandlesKHR(DeviceManager.vkDevice, pipelineHandle, 0, groupCount, handles) != VK_SUCCESS) { + MemoryUtil.memFree(handles); + throw new RuntimeException("Failed to get ray tracing shader group handles"); + } + + ByteBuffer sbtData = MemoryUtil.memAlloc(sbtSize); + MemoryUtil.memSet(MemoryUtil.memAddress(sbtData), (byte) 0, sbtSize); + for (int i = 0; i < groupCount; i++) { + long src = MemoryUtil.memAddress(handles) + (long) i * handleSize; + long dst = MemoryUtil.memAddress(sbtData) + (long) i * this.sbtStride; + MemoryUtil.memCopy(src, dst, handleSize); + } + MemoryUtil.memFree(handles); + + this.shaderBindingTable = new Buffer(VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, MemoryTypes.HOST_MEM); + this.shaderBindingTable.createBuffer(sbtSize); + this.shaderBindingTable.copyBuffer(sbtData, sbtSize); + MemoryUtil.memFree(sbtData); + + VkBufferDeviceAddressInfo bufferDeviceAddressInfo = VkBufferDeviceAddressInfo.calloc(stack); + bufferDeviceAddressInfo.sType$Default(); + bufferDeviceAddressInfo.buffer(this.shaderBindingTable.getId()); + this.sbtBufferAddress = vkGetBufferDeviceAddress(DeviceManager.vkDevice, bufferDeviceAddressInfo); + } + } + + public long getHandle() { + return this.pipelineHandle; + } + + public long getSbtBufferAddress() { + return sbtBufferAddress; + } + + public int getSbtStride() { + return sbtStride; + } + + @Override + public void cleanUp() { + vkDestroyShaderModule(DeviceManager.vkDevice, raygenShaderModule, null); + vkDestroyShaderModule(DeviceManager.vkDevice, missShaderModule, null); + vkDestroyShaderModule(DeviceManager.vkDevice, chitShaderModule, null); + + destroyDescriptorSets(); + vkDestroyPipeline(DeviceManager.vkDevice, pipelineHandle, null); + vkDestroyDescriptorSetLayout(DeviceManager.vkDevice, descriptorSetLayout, null); + vkDestroyPipelineLayout(DeviceManager.vkDevice, pipelineLayout, null); + + this.shaderBindingTable.scheduleFree(); + + PIPELINES.remove(this); + //Renderer.getInstance().removeUsedPipeline(this); + } + + public static class Builder extends Pipeline.Builder { + SPIRVUtils.SPIRV raygenShaderSPIRV, missShaderSPIRV, chitShaderSPIRV; + + public Builder(String shaderPath) { + super(null, shaderPath); + } + + public Builder setRaygenShaderSPIRV(SPIRVUtils.SPIRV spirv) { + this.raygenShaderSPIRV = spirv; + return this; + } + + public Builder setMissShaderSPIRV(SPIRVUtils.SPIRV spirv) { + this.missShaderSPIRV = spirv; + return this; + } + + public Builder setChitShaderSPIRV(SPIRVUtils.SPIRV spirv) { + this.chitShaderSPIRV = spirv; + return this; + } + + public RayTracingPipeline createRayTracingPipeline() { + return new RayTracingPipeline(this); + } + } +} diff --git a/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java b/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java index 05c95e547..d27eadda1 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/SPIRVUtils.java @@ -24,15 +24,12 @@ public class SPIRVUtils { private static final boolean DEBUG = false; private static final boolean OPTIMIZATIONS = true; - - private static long compiler; - private static long options; - //The dedicated Includer and Releaser Inner Classes used to Initialise #include Support for ShaderC private static final ShaderIncluder SHADER_INCLUDER = new ShaderIncluder(); private static final ShaderReleaser SHADER_RELEASER = new ShaderReleaser(); private static final long pUserData = 0; - + private static long compiler; + private static long options; private static ObjectArrayList includePaths; static { @@ -55,8 +52,7 @@ private static void initCompiler() { if (OPTIMIZATIONS) shaderc_compile_options_set_optimization_level(options, shaderc_optimization_level_performance); - if (DEBUG) - shaderc_compile_options_set_generate_debug_info(options); + if (DEBUG) shaderc_compile_options_set_generate_debug_info(options); shaderc_compile_options_set_target_env(options, shaderc_env_version_vulkan_1_2, VK12.VK_API_VERSION_1_2); shaderc_compile_options_set_include_callbacks(options, SHADER_INCLUDER, SHADER_RELEASER, pUserData); @@ -68,8 +64,7 @@ private static void initCompiler() { public static void addIncludePath(String path) { URL url = SPIRVUtils.class.getResource(path); - if (url != null) - includePaths.add(url.toExternalForm()); + if (url != null) includePaths.add(url.toExternalForm()); } public static SPIRV compileShader(String filename, String source, ShaderKind shaderKind) { @@ -84,19 +79,14 @@ public static SPIRV compileShader(String filename, String source, ShaderKind sha } if (shaderc_result_get_compilation_status(result) != shaderc_compilation_status_success) { - throw new RuntimeException( - "Failed to compile shader " + filename + " into SPIR-V:\n" + shaderc_result_get_error_message( - result)); + throw new RuntimeException("Failed to compile shader " + filename + " into SPIR-V:\n" + shaderc_result_get_error_message(result)); } return new SPIRV(result, shaderc_result_get_bytes(result)); } public enum ShaderKind { - VERTEX_SHADER(shaderc_glsl_vertex_shader), - GEOMETRY_SHADER(shaderc_glsl_geometry_shader), - FRAGMENT_SHADER(shaderc_glsl_fragment_shader), - COMPUTE_SHADER(shaderc_glsl_compute_shader); + VERTEX_SHADER(shaderc_glsl_vertex_shader), GEOMETRY_SHADER(shaderc_glsl_geometry_shader), FRAGMENT_SHADER(shaderc_glsl_fragment_shader), COMPUTE_SHADER(shaderc_glsl_compute_shader), RAYGEN_SHADER(shaderc_glsl_raygen_shader), MISS_SHADER(shaderc_glsl_miss_shader), CLOSEST_HIT_SHADER(shaderc_glsl_closesthit_shader); private final int kind; @@ -123,10 +113,7 @@ public long invoke(long user_data, long requested_source, int type, long request if (Files.exists(path)) { byte[] bytes = Files.readAllBytes(path); - return ShadercIncludeResult.malloc(stack) - .source_name(stack.ASCII(requested)) - .content(stack.bytes(bytes)) - .user_data(user_data).address(); + return ShadercIncludeResult.malloc(stack).source_name(stack.ASCII(requested)).content(stack.bytes(bytes)).user_data(user_data).address(); } } } catch (IOException | URISyntaxException e) { diff --git a/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java b/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java index 7ca193a65..7d0bf14cf 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/Uniforms.java @@ -28,14 +28,14 @@ public static void setupDefaultUniforms() { //Vec1i vec1i_uniformMap.put("EndPortalLayers", () -> 15); - vec1i_uniformMap.put("FogShape", () -> RenderSystem.getShaderFogShape().getIndex()); + vec1i_uniformMap.put("FogShape", VRenderSystem::getFogShapeIndex); //Vec1 - vec1f_uniformMap.put("FogStart", RenderSystem::getShaderFogStart); - vec1f_uniformMap.put("FogEnd", RenderSystem::getShaderFogEnd); + vec1f_uniformMap.put("FogStart", VRenderSystem::getFogStart); + vec1f_uniformMap.put("FogEnd", VRenderSystem::getFogEnd); vec1f_uniformMap.put("LineWidth", RenderSystem::getShaderLineWidth); - vec1f_uniformMap.put("GameTime", RenderSystem::getShaderGameTime); - vec1f_uniformMap.put("GlintAlpha", RenderSystem::getShaderGlintAlpha); + vec1f_uniformMap.put("GameTime", VRenderSystem::getShaderGameTime); + vec1f_uniformMap.put("GlintAlpha", VRenderSystem::getGlintAlpha); vec1f_uniformMap.put("AlphaCutout", () -> VRenderSystem.alphaCutout); //Vec2 diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/GlslConverter.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/GlslConverter.java index 50d2302a7..affdfad73 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/converter/GlslConverter.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/GlslConverter.java @@ -3,10 +3,12 @@ import net.vulkanmod.vulkan.shader.descriptor.ImageDescriptor; import net.vulkanmod.vulkan.shader.descriptor.UBO; -import java.util.*; +import java.util.Arrays; +import java.util.List; +import java.util.StringTokenizer; public class GlslConverter { - + ShaderStage shaderStage; private State state; @@ -62,7 +64,7 @@ private StringBuilder processShaderFile(ShaderStage stage, String shader) { var lines2 = line.splitWithDelimiters(";", 0); int matchingFor = 0; - for (int i = 0; i < lines2.length;) { + for (int i = 0; i < lines2.length; ) { StringBuilder line2 = new StringBuilder(lines2[i]); i++; @@ -94,8 +96,7 @@ private StringBuilder processShaderFile(ShaderStage stage, String shader) { } } - } - else { + } else { String parsedLine = this.parseLine(line); if (parsedLine != null) { out.append(parsedLine); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/InputOutputParser.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/InputOutputParser.java index cde9e5eff..d69754a7f 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/converter/InputOutputParser.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/InputOutputParser.java @@ -10,11 +10,9 @@ public class InputOutputParser { private final GlslConverter converterInstance; - private VertexFormat vertexFormat; - private final AttributeSet vertInAttributes = new AttributeSet(); private final AttributeSet vertOutAttributes = new AttributeSet(); - + private VertexFormat vertexFormat; private GlslConverter.ShaderStage shaderStage; private int currentLocation = 0; @@ -37,16 +35,15 @@ else if (this.name == null) { this.name = token; - if(this.shaderStage == GlslConverter.ShaderStage.Vertex) { + if (this.shaderStage == GlslConverter.ShaderStage.Vertex) { switch (this.ioType) { case "in" -> this.vertInAttributes.add(this.type, this.name); case "out" -> this.vertOutAttributes.add(this.type, this.name); } - } - else { + } else { switch (this.ioType) { case "in" -> { - if(!this.vertOutAttributes.contains(this.type, this.name)) + if (!this.vertOutAttributes.contains(this.type, this.name)) throw new RuntimeException("fragment in attribute does not match vertex output"); } case "out" -> { @@ -71,22 +68,21 @@ public String createInOutCode() { //TODO StringBuilder builder = new StringBuilder(); - if(this.shaderStage == GlslConverter.ShaderStage.Vertex) { + if (this.shaderStage == GlslConverter.ShaderStage.Vertex) { //In - for(Attribute attribute : this.vertInAttributes.attributes) { + for (Attribute attribute : this.vertInAttributes.attributes) { builder.append(String.format("layout(location = %d) in %s %s;\n", attribute.location, attribute.type, attribute.name)); } builder.append("\n"); //Out - for(Attribute attribute : this.vertOutAttributes.attributes) { + for (Attribute attribute : this.vertOutAttributes.attributes) { builder.append(String.format("layout(location = %d) out %s %s;\n", attribute.location, attribute.type, attribute.name)); } builder.append("\n"); - } - else { + } else { //In - for(Attribute attribute : this.vertOutAttributes.attributes) { + for (Attribute attribute : this.vertOutAttributes.attributes) { builder.append(String.format("layout(location = %d) in %s %s;\n", attribute.location, attribute.type, attribute.name)); } builder.append("\n"); @@ -102,7 +98,8 @@ public void setShaderStage(GlslConverter.ShaderStage shaderStage) { this.shaderStage = shaderStage; } - public record Attribute(int location, String type, String name) {} + public record Attribute(int location, String type, String name) { + } static class AttributeSet { List attributes = new ObjectArrayList<>(); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/converter/UniformParser.java b/src/main/java/net/vulkanmod/vulkan/shader/converter/UniformParser.java index 0fe03111e..9779db409 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/converter/UniformParser.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/converter/UniformParser.java @@ -13,9 +13,8 @@ public class UniformParser { private final GlslConverter converterInstance; private final StageUniforms[] stageUniforms = new StageUniforms[GlslConverter.ShaderStage.values().length]; - private StageUniforms currentUniforms; List globalUniforms = new ArrayList<>(); - + private StageUniforms currentUniforms; private String type; private String name; @@ -29,14 +28,20 @@ public UniformParser(GlslConverter converterInstance) { } } + public static String removeSemicolon(String s) { + int last = s.length() - 1; + if ((s.charAt(last)) != ';') + throw new IllegalArgumentException("last char is not ;"); + return s.substring(0, last); + } + public boolean parseToken(String token) { if (token.matches("uniform")) return false; if (this.type == null) { this.type = token; - } - else if (this.name == null) { + } else if (this.name == null) { token = removeSemicolon(token); this.name = token; @@ -46,8 +51,7 @@ else if (this.name == null) { if ("sampler2D".equals(this.type)) { if (!this.currentUniforms.samplers.contains(uniform)) this.currentUniforms.samplers.add(uniform); - } - else { + } else { if (!this.globalUniforms.contains(uniform)) this.globalUniforms.add(uniform); } @@ -89,7 +93,7 @@ public String createSamplersCode(GlslConverter.ShaderStage shaderStage) { for (ImageDescriptor imageDescriptor : this.imageDescriptors) { builder.append(String.format("layout(binding = %d) uniform %s %s;\n", imageDescriptor.getBinding(), - imageDescriptor.qualifier, imageDescriptor.name)); + imageDescriptor.qualifier, imageDescriptor.name)); } builder.append("\n"); @@ -128,13 +132,6 @@ private List createSamplerList() { return imageDescriptors; } - public static String removeSemicolon(String s) { - int last = s.length() - 1; - if ((s.charAt(last)) != ';') - throw new IllegalArgumentException("last char is not ;"); - return s.substring(0, last); - } - public List getGlobalUniforms() { return globalUniforms; } @@ -143,16 +140,16 @@ public List getSamplers() { return this.imageDescriptors; } + enum State { + Uniform, + Sampler, + None + } + public record Uniform(String type, String name) { } private static class StageUniforms { List samplers = new ArrayList<>(); } - - enum State { - Uniform, - Sampler, - None - } } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/Descriptor.java b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/Descriptor.java index 2685ccd0e..2a8fd774a 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/Descriptor.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/Descriptor.java @@ -2,9 +2,9 @@ public interface Descriptor { - int getBinding(); + int getBinding(); - int getType(); + int getType(); - int getStages(); + int getStages(); } diff --git a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ImageDescriptor.java b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ImageDescriptor.java index 40ad7b070..f9c2f0f8c 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ImageDescriptor.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/descriptor/ImageDescriptor.java @@ -7,13 +7,12 @@ public class ImageDescriptor implements Descriptor { - private final int descriptorType; - private final int binding; public final String qualifier; public final String name; public final int imageIdx; - public final boolean isStorageImage; + private final int descriptorType; + private final int binding; public boolean useSampler; public boolean isReadOnlyLayout; private int layout; @@ -50,23 +49,23 @@ public int getStages() { return VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT; } + public int getLayout() { + return layout; + } + public void setLayout(int layout) { this.layout = layout; this.isReadOnlyLayout = layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; } - public int getLayout() { - return layout; + public int getMipLevel() { + return mipLevel; } public void setMipLevel(int mipLevel) { this.mipLevel = mipLevel; } - public int getMipLevel() { - return mipLevel; - } - public VulkanImage getImage() { return VTextureSelector.getImage(this.imageIdx); } @@ -74,7 +73,7 @@ public VulkanImage getImage() { public long getImageView(VulkanImage image) { long view; - if(mipLevel == -1) + if (mipLevel == -1) view = image.getImageView(); else view = image.getLevelImageView(mipLevel); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java index 11560c621..94e794675 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/AlignedStruct.java @@ -13,8 +13,7 @@ public abstract class AlignedStruct { protected AlignedStruct(List infoList, int size) { this.size = size; - if (infoList == null) - return; + if (infoList == null) return; for (Uniform.Info info : infoList) { Uniform uniform = Uniform.createField(info); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java index 8c1509df1..118a773ed 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Uniform.java @@ -8,10 +8,9 @@ public class Uniform { protected Supplier values; - - Info info; protected long offset; protected int size; + Info info; Uniform(Info info) { this.info = info; @@ -21,24 +20,6 @@ public class Uniform { this.setupSupplier(); } - protected void setupSupplier() { - this.values = this.info.bufferSupplier; - } - - public void setSupplier(Supplier supplier) { - this.values = supplier; - } - - public String getName() { - return this.info.name; - } - - void update(long ptr) { - MappedBuffer src = values.get(); - - MemoryUtil.memCopy(src.ptr, ptr + this.offset, this.size); - } - public static Uniform createField(Info info) { return switch (info.type) { case "mat4", "vec3", "vec4", "vec2" -> new Uniform(info); @@ -49,20 +30,6 @@ public static Uniform createField(Info info) { }; } - public int getOffset() { - return info.offset; - } - - public int getSize() { return info.size; } - - public Info getInfo() { - return info; - } - - public String toString() { - return String.format("%s: %s offset: %d", info.type, info.name, info.offset); - } - //TODO public static Info createUniformInfo(String type, String name, int count) { return switch (type) { @@ -95,6 +62,40 @@ public static Info createUniformInfo(String type, String name) { }; } + protected void setupSupplier() { + this.values = this.info.bufferSupplier; + } + + public void setSupplier(Supplier supplier) { + this.values = supplier; + } + + public String getName() { + return this.info.name; + } + + void update(long ptr) { + MappedBuffer src = values.get(); + + MemoryUtil.memCopy(src.ptr, ptr + this.offset, this.size); + } + + public int getOffset() { + return info.offset; + } + + public int getSize() { + return info.size; + } + + public Info getInfo() { + return info; + } + + public String toString() { + return String.format("%s: %s offset: %d", info.type, info.name, info.offset); + } + public static class Info { public final String type; public final String name; @@ -113,7 +114,9 @@ public static class Info { this.size = size; } - int getSizeBytes() { return 4 * this.size; } + int getSizeBytes() { + return 4 * this.size; + } int computeAlignmentOffset(int builderOffset) { return this.offset = builderOffset + ((align - (builderOffset % align)) % align); diff --git a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1i.java b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1i.java index 700fd00bf..954934708 100644 --- a/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1i.java +++ b/src/main/java/net/vulkanmod/vulkan/shader/layout/Vec1i.java @@ -1,8 +1,6 @@ package net.vulkanmod.vulkan.shader.layout; -import net.vulkanmod.vulkan.shader.Uniforms; import net.vulkanmod.vulkan.util.MappedBuffer; -import org.apache.commons.lang3.Validate; import org.lwjgl.system.MemoryUtil; import java.util.function.Supplier; diff --git a/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java b/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java index c6b4ea2a0..092f0bb6d 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/ImageUtil.java @@ -17,9 +17,7 @@ public abstract class ImageUtil { - public static void copyBufferToImageCmd(MemoryStack stack, VkCommandBuffer commandBuffer, long buffer, long image, - int mipLevel, int width, int height, int xOffset, int yOffset, - int bufferOffset, int bufferRowLenght, int bufferImageHeight) { + public static void copyBufferToImageCmd(MemoryStack stack, VkCommandBuffer commandBuffer, long buffer, long image, int mipLevel, int width, int height, int xOffset, int yOffset, int bufferOffset, int bufferRowLenght, int bufferImageHeight) { VkBufferImageCopy.Buffer region = VkBufferImageCopy.calloc(1, stack); region.bufferOffset(bufferOffset); region.bufferRowLength(bufferRowLenght); @@ -44,34 +42,27 @@ public static void downloadTexture(VulkanImage image, long ptr) { LongBuffer pStagingBuffer = stack.mallocLong(1); PointerBuffer pStagingAllocation = stack.pointers(0L); - MemoryManager.getInstance().createBuffer(imageSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - pStagingBuffer, pStagingAllocation); + MemoryManager.getInstance().createBuffer(imageSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, pStagingBuffer, pStagingAllocation); - copyImageToBufferCmd(stack, commandBuffer.getHandle(), pStagingBuffer.get(0), image.getId(), 0, image.width, - image.height, 0, 0, 0, 0, 0); + copyImageToBufferCmd(stack, commandBuffer.getHandle(), pStagingBuffer.get(0), image.getId(), 0, image.width, image.height, 0, 0, 0, 0, 0); image.transitionImageLayout(stack, commandBuffer.getHandle(), prevLayout); long fence = DeviceManager.getGraphicsQueue().submitCommands(commandBuffer); vkWaitForFences(DeviceManager.vkDevice, fence, true, VUtil.UINT64_MAX); - MemoryManager.MapAndCopy(pStagingAllocation.get(0), - (data) -> VUtil.memcpy(data.getByteBuffer(0, (int) imageSize), ptr)); + MemoryManager.MapAndCopy(pStagingAllocation.get(0), (data) -> VUtil.memcpy(data.getByteBuffer(0, (int) imageSize), ptr)); MemoryManager.freeBuffer(pStagingBuffer.get(0), pStagingAllocation.get(0)); } } - public static void copyImageToBuffer(VulkanImage image, Buffer buffer, int mipLevel, - int width, int height, int xOffset, int yOffset, - int bufferOffset, int bufferRowLength, int bufferImageHeight) { + public static void copyImageToBuffer(VulkanImage image, Buffer buffer, int mipLevel, int width, int height, int xOffset, int yOffset, int bufferOffset, int bufferRowLength, int bufferImageHeight) { try (MemoryStack stack = stackPush()) { int prevLayout = image.getCurrentLayout(); CommandPool.CommandBuffer commandBuffer = DeviceManager.getGraphicsQueue().beginCommands(); image.transitionImageLayout(stack, commandBuffer.getHandle(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - copyImageToBufferCmd(stack, commandBuffer.getHandle(), buffer.getId(), image.getId(), mipLevel, width, - height, xOffset, yOffset, bufferOffset, bufferRowLength, bufferImageHeight); + copyImageToBufferCmd(stack, commandBuffer.getHandle(), buffer.getId(), image.getId(), mipLevel, width, height, xOffset, yOffset, bufferOffset, bufferRowLength, bufferImageHeight); image.transitionImageLayout(stack, commandBuffer.getHandle(), prevLayout); long fence = DeviceManager.getGraphicsQueue().submitCommands(commandBuffer); @@ -79,9 +70,7 @@ public static void copyImageToBuffer(VulkanImage image, Buffer buffer, int mipLe } } - public static void copyImageToBufferCmd(MemoryStack stack, VkCommandBuffer commandBuffer, long buffer, long image, - int mipLevel, int width, int height, int xOffset, int yOffset, int bufferOffset, - int bufferRowLength, int bufferImageHeight) { + public static void copyImageToBufferCmd(MemoryStack stack, VkCommandBuffer commandBuffer, long buffer, long image, int mipLevel, int width, int height, int xOffset, int yOffset, int bufferOffset, int bufferRowLength, int bufferImageHeight) { VkBufferImageCopy.Buffer region = VkBufferImageCopy.calloc(1, stack); region.bufferOffset(bufferOffset); region.bufferRowLength(bufferRowLength); @@ -113,19 +102,13 @@ public static void blitFramebuffer(VulkanImage dstImage, int srcX0, int srcY0, i VkImageBlit.Buffer blit = VkImageBlit.calloc(1, stack); blit.srcOffsets(0, VkOffset3D.calloc(stack).set(0, 0, 0)); blit.srcOffsets(1, VkOffset3D.calloc(stack).set(srcImage.width, srcImage.height, 1)); - blit.srcSubresource() - .aspectMask(VK_IMAGE_ASPECT_COLOR_BIT) - .mipLevel(0) - .baseArrayLayer(0) - .layerCount(1); + blit.srcSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT).mipLevel(0).baseArrayLayer(0).layerCount(1); blit.dstOffsets(0, VkOffset3D.calloc(stack).set(0, 0, 0)); blit.dstOffsets(1, VkOffset3D.calloc(stack).set(dstImage.width, dstImage.height, 1)); - blit.dstSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT).mipLevel(0).baseArrayLayer(0) - .layerCount(1); + blit.dstSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT).mipLevel(0).baseArrayLayer(0).layerCount(1); - vkCmdBlitImage(commandBuffer, srcImage.getId(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - dstImage.getId(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, blit, VK_FILTER_LINEAR); + vkCmdBlitImage(commandBuffer, srcImage.getId(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dstImage.getId(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, blit, VK_FILTER_LINEAR); dstImage.transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); @@ -164,27 +147,20 @@ public static void generateMipmaps(VulkanImage image) { barrier.srcAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT); barrier.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT); - vkCmdPipelineBarrier(commandBuffer.getHandle(), VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, null, null, barrier); + vkCmdPipelineBarrier(commandBuffer.getHandle(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, null, null, barrier); prevLevel = level - 1; VkImageBlit.Buffer blit = VkImageBlit.calloc(1, stack); blit.srcOffsets(0, VkOffset3D.calloc(stack).set(0, 0, 0)); blit.srcOffsets(1, VkOffset3D.calloc(stack).set(image.width >> prevLevel, image.height >> prevLevel, 1)); - blit.srcSubresource() - .aspectMask(VK_IMAGE_ASPECT_COLOR_BIT) - .mipLevel(prevLevel) - .baseArrayLayer(0) - .layerCount(1); + blit.srcSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT).mipLevel(prevLevel).baseArrayLayer(0).layerCount(1); blit.dstOffsets(0, VkOffset3D.calloc(stack).set(0, 0, 0)); blit.dstOffsets(1, VkOffset3D.calloc(stack).set(image.width >> level, image.height >> level, 1)); - blit.dstSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT).mipLevel(level).baseArrayLayer(0) - .layerCount(1); + blit.dstSubresource().aspectMask(VK_IMAGE_ASPECT_COLOR_BIT).mipLevel(level).baseArrayLayer(0).layerCount(1); - vkCmdBlitImage(commandBuffer.getHandle(), image.getId(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - image.getId(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, blit, VK_FILTER_LINEAR); + vkCmdBlitImage(commandBuffer.getHandle(), image.getId(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, image.getId(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, blit, VK_FILTER_LINEAR); } @@ -206,21 +182,13 @@ public static void generateMipmaps(VulkanImage image) { barrier.srcAccessMask(VK_ACCESS_TRANSFER_WRITE_BIT); barrier.dstAccessMask(VK_ACCESS_SHADER_READ_BIT); - vkCmdPipelineBarrier(commandBuffer.getHandle(), - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, - null, null, - barrier); + vkCmdPipelineBarrier(commandBuffer.getHandle(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, null, null, barrier); barrier.oldLayout(VK_IMAGE_USAGE_TRANSFER_DST_BIT); barrier.subresourceRange().baseMipLevel(image.mipLevels - 1); barrier.subresourceRange().levelCount(1); - vkCmdPipelineBarrier(commandBuffer.getHandle(), - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, - null, null, - barrier); + vkCmdPipelineBarrier(commandBuffer.getHandle(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, null, null, barrier); image.setCurrentLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); diff --git a/src/main/java/net/vulkanmod/vulkan/texture/SamplerManager.java b/src/main/java/net/vulkanmod/vulkan/texture/SamplerManager.java index f58fb4255..3fd4cf26f 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/SamplerManager.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/SamplerManager.java @@ -17,8 +17,13 @@ import static org.lwjgl.vulkan.VK12.VK_SAMPLER_REDUCTION_MODE_MIN; public abstract class SamplerManager { + public static final byte LINEAR_FILTERING_BIT = 0b1; + public static final byte CLAMP_BIT = 0b10; + public static final byte USE_MIPMAPS_BIT = 0b100; + public static final byte MIPMAP_LINEAR_FILTERING_BIT = 0b1000; + public static final byte REDUCTION_MIN_BIT = 0b10000; + public static final byte REDUCTION_MAX_BIT = 0b100000; static final float MIP_BIAS = -0.5f; - static final Short2LongMap SAMPLERS = new Short2LongOpenHashMap(); public static long getTextureSampler(byte maxLod, byte flags) { @@ -34,9 +39,7 @@ public static long getTextureSampler(byte maxLod, byte flags) { } private static long createTextureSampler(byte maxLod, byte flags) { - Validate.isTrue( - (flags & (REDUCTION_MIN_BIT | REDUCTION_MAX_BIT)) != (REDUCTION_MIN_BIT | REDUCTION_MAX_BIT) - ); + Validate.isTrue((flags & (REDUCTION_MIN_BIT | REDUCTION_MAX_BIT)) != (REDUCTION_MIN_BIT | REDUCTION_MAX_BIT)); try (MemoryStack stack = stackPush()) { @@ -106,11 +109,4 @@ public static void cleanUp() { vkDestroySampler(DeviceManager.vkDevice, id, null); } } - - public static final byte LINEAR_FILTERING_BIT = 0b1; - public static final byte CLAMP_BIT = 0b10; - public static final byte USE_MIPMAPS_BIT = 0b100; - public static final byte MIPMAP_LINEAR_FILTERING_BIT = 0b1000; - public static final byte REDUCTION_MIN_BIT = 0b10000; - public static final byte REDUCTION_MAX_BIT = 0b100000; } diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java index dfc85ec77..34972e230 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VTextureSelector.java @@ -1,7 +1,8 @@ package net.vulkanmod.vulkan.texture; +import com.mojang.blaze3d.opengl.GlTextureView; import com.mojang.blaze3d.systems.RenderSystem; -import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite; +import com.mojang.blaze3d.textures.GpuTextureView; import net.vulkanmod.Initializer; import net.vulkanmod.gl.VkGlTexture; import net.vulkanmod.vulkan.shader.Pipeline; @@ -47,8 +48,7 @@ public static void bindImage(int i, VulkanImage texture, int level) { public static void uploadSubTexture(int mipLevel, int width, int height, int xOffset, int yOffset, int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, ByteBuffer buffer) { VulkanImage texture = boundTextures[activeTexture]; - if(texture == null) - throw new NullPointerException("Texture is null at index: " + activeTexture); + if (texture == null) throw new NullPointerException("Texture is null at index: " + activeTexture); texture.uploadSubTextureAsync(mipLevel, width, height, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, unpackRowLength, buffer); } @@ -70,19 +70,30 @@ public static int getTextureIdx(String name) { public static void bindShaderTextures(Pipeline pipeline) { var imageDescriptors = pipeline.getImageDescriptors(); - for (ImageDescriptor state : imageDescriptors) { - final int shaderTexture = RenderSystem.getShaderTexture(state.imageIdx); + for (ImageDescriptor descriptor : imageDescriptors) { + VulkanImage image = resolveImage(RenderSystem.getShaderTexture(descriptor.imageIdx)); - VkGlTexture texture = VkGlTexture.getTexture(shaderTexture); - - if (texture != null && texture.getVulkanImage() != null) { - VTextureSelector.bindTexture(state.imageIdx, texture.getVulkanImage()); + if (image != null) { + VTextureSelector.bindTexture(descriptor.imageIdx, image); + } else { + VTextureSelector.bindTexture(descriptor.imageIdx, whiteTexture); } - else { - texture = VkGlTexture.getTexture(MissingTextureAtlasSprite.getTexture().getId()); - VTextureSelector.bindTexture(state.imageIdx, texture.getVulkanImage()); + } + } + + private static VulkanImage resolveImage(GpuTextureView view) { + if (view == null) { + return null; + } + + if (view instanceof GlTextureView glView) { + VkGlTexture texture = VkGlTexture.getTexture(glView.texture().glId()); + if (texture != null) { + return texture.getVulkanImage(); } } + + return null; } public static VulkanImage getImage(int i) { @@ -99,8 +110,7 @@ public static void setOverlayTexture(VulkanImage texture) { public static void setActiveTexture(int activeTexture) { if (activeTexture < 0 || activeTexture >= SIZE) { - Initializer.LOGGER.error( - String.format("On Texture binding: index %d out of range [0, %d]", activeTexture, SIZE - 1)); + Initializer.LOGGER.error(String.format("On Texture binding: index %d out of range [0, %d]", activeTexture, SIZE - 1)); } VTextureSelector.activeTexture = activeTexture; diff --git a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java index e44790bbc..905cc2478 100644 --- a/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java +++ b/src/main/java/net/vulkanmod/vulkan/texture/VulkanImage.java @@ -24,10 +24,8 @@ import static org.lwjgl.vulkan.VK10.*; public class VulkanImage { - public static int DefaultFormat = VK_FORMAT_R8G8B8A8_UNORM; - private static final VkDevice DEVICE = Vulkan.getVkDevice(); - + public static int DefaultFormat = VK_FORMAT_R8G8B8A8_UNORM; public final String name; public final int format; public final int aspect; @@ -100,12 +98,7 @@ public static VulkanImage createTextureImage(Builder builder) { } public static VulkanImage createDepthImage(int format, int width, int height, int usage, boolean blur, boolean clamp) { - VulkanImage image = VulkanImage.builder(width, height) - .setFormat(format) - .setUsage(usage) - .setLinearFiltering(blur) - .setClamp(clamp) - .createVulkanImage(); + VulkanImage image = VulkanImage.builder(width, height).setFormat(format).setUsage(usage).setLinearFiltering(blur).setClamp(clamp).createVulkanImage(); return image; } @@ -116,48 +109,19 @@ public static VulkanImage createWhiteTexture() { ByteBuffer buffer = stack.malloc(4); buffer.putInt(0, i); - VulkanImage image = VulkanImage.builder(1, 1) - .setFormat(DefaultFormat) - .setUsage(VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT) - .setLinearFiltering(false) - .setClamp(false) - .createVulkanImage(); + VulkanImage image = VulkanImage.builder(1, 1).setFormat(DefaultFormat).setUsage(VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT).setLinearFiltering(false).setClamp(false).createVulkanImage(); image.uploadSubTextureAsync(0, image.width, image.height, 0, 0, 0, 0, 0, buffer); return image; // return createTextureImage(1, 1, 4, false, false, buffer); } } - private void createImage() { - try (MemoryStack stack = stackPush()) { - LongBuffer pTextureImage = stack.mallocLong(1); - PointerBuffer pAllocation = stack.pointers(0L); - - MemoryManager.getInstance().createImage(width, height, mipLevels, - format, VK_IMAGE_TILING_OPTIMAL, - usage, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, - pTextureImage, - pAllocation); - - id = pTextureImage.get(0); - allocation = pAllocation.get(0); - - MemoryManager.addImage(this); - - if (this.name != null) { - Vulkan.setDebugLabel(stack, VK_OBJECT_TYPE_IMAGE, pTextureImage.get(), this.name); - } - } - } - public static int getAspect(int format) { return switch (format) { case VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D32_SFLOAT_S8_UINT -> VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; - case VK_FORMAT_X8_D24_UNORM_PACK32, VK_FORMAT_D32_SFLOAT, - VK_FORMAT_D16_UNORM -> VK_IMAGE_ASPECT_DEPTH_BIT; + case VK_FORMAT_X8_D24_UNORM_PACK32, VK_FORMAT_D32_SFLOAT, VK_FORMAT_D16_UNORM -> VK_IMAGE_ASPECT_DEPTH_BIT; default -> VK_IMAGE_ASPECT_COLOR_BIT; }; @@ -165,9 +129,8 @@ public static int getAspect(int format) { public static boolean isDepthFormat(int format) { return switch (format) { - case VK_FORMAT_X8_D24_UNORM_PACK32, VK_FORMAT_D24_UNORM_S8_UINT, - VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, - VK_FORMAT_D16_UNORM -> true; + case VK_FORMAT_X8_D24_UNORM_PACK32, VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D32_SFLOAT, + VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D16_UNORM -> true; default -> false; }; } @@ -201,94 +164,21 @@ public static long createImageView(long image, int format, int aspectFlags, int } } - public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffset, int yOffset, int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, ByteBuffer buffer) { - this.uploadSubTextureAsync(mipLevel, width, height, - xOffset, yOffset, unpackSkipRows, unpackSkipPixels, unpackRowLength, - MemoryUtil.memAddress(buffer)); - } - - public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffset, int yOffset, int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, long srcPtr) { - long uploadSize = (long) (unpackRowLength * height - unpackSkipPixels) * this.formatSize; - - StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); - - // Use a temporary staging buffer if the upload size is greater than - // the default staging buffer - if (uploadSize > stagingBuffer.getBufferSize()) { - stagingBuffer = new StagingBuffer(uploadSize); - stagingBuffer.scheduleFree(); - } - - srcPtr += ((long) unpackRowLength * unpackSkipRows + unpackSkipPixels) * this.formatSize; - - stagingBuffer.align(this.formatSize); - stagingBuffer.copyBuffer((int) uploadSize, srcPtr); - - long bufferId = stagingBuffer.getId(); - - VkCommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer().getHandle(); - try (MemoryStack stack = stackPush()) { - transferDstLayout(stack, commandBuffer); - - final int srcOffset = (int) (stagingBuffer.getOffset()); - - ImageUtil.copyBufferToImageCmd(stack, commandBuffer, bufferId, this.id, mipLevel, width, height, xOffset, yOffset, - srcOffset, unpackRowLength, height); - } - } - - private void transferDstLayout(MemoryStack stack, VkCommandBuffer commandBuffer) { - transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); - } - - public void readOnlyLayout() { - if (this.currentLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) - return; - - try (MemoryStack stack = MemoryStack.stackPush()) { - if (Renderer.getInstance().getBoundRenderPass() != null) { - CommandPool.CommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer(); - VkCommandBuffer vkCommandBuffer = commandBuffer.getHandle(); - - readOnlyLayout(stack, vkCommandBuffer); - } - else { - readOnlyLayout(stack, Renderer.getCommandBuffer()); - } + public static void transitionImageLayout(MemoryStack stack, VkCommandBuffer commandBuffer, VulkanImage image, int newLayout) { + try (java.lang.foreign.Arena arena = java.lang.foreign.Arena.ofConfined()) { + transitionImageLayout(arena, commandBuffer, image, newLayout); } } - public void readOnlyLayout(MemoryStack stack, VkCommandBuffer commandBuffer) { - transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - } - - public void updateTextureSampler(boolean blur, boolean clamp, boolean mipmaps) { - byte flags = blur ? LINEAR_FILTERING_BIT : 0; - flags |= clamp ? CLAMP_BIT : 0; - flags |= (byte) (mipmaps ? USE_MIPMAPS_BIT | MIPMAP_LINEAR_FILTERING_BIT : 0); - - this.updateTextureSampler(flags); - } - - public void updateTextureSampler(byte flags) { - updateTextureSampler(this.mipLevels - 1, flags); - } - - public void updateTextureSampler(int maxLod, byte flags) { - this.sampler = SamplerManager.getTextureSampler((byte) maxLod, flags); - } - - public void transitionImageLayout(MemoryStack stack, VkCommandBuffer commandBuffer, int newLayout) { - transitionImageLayout(stack, commandBuffer, this, newLayout); - } - - public static void transitionImageLayout(MemoryStack stack, VkCommandBuffer commandBuffer, VulkanImage image, int newLayout) { + public static void transitionImageLayout(java.lang.foreign.Arena arena, VkCommandBuffer commandBuffer, VulkanImage image, int newLayout) { if (image.currentLayout == newLayout) { -// System.out.println("new layout is equal to current layout"); return; } - int sourceStage, srcAccessMask, destinationStage, dstAccessMask = 0; + int sourceStage; + int srcAccessMask; + int destinationStage; + int dstAccessMask; switch (image.currentLayout) { case VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR -> { @@ -340,25 +230,35 @@ public static void transitionImageLayout(MemoryStack stack, VkCommandBuffer comm destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; } case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR -> { + dstAccessMask = 0; destinationStage = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; } default -> throw new RuntimeException("Unexpected value:" + newLayout); } - transitionLayout(stack, commandBuffer, image, image.currentLayout, newLayout, - sourceStage, srcAccessMask, destinationStage, dstAccessMask); + transitionLayout(arena, commandBuffer, image, image.currentLayout, newLayout, sourceStage, srcAccessMask, destinationStage, dstAccessMask); } - public static void transitionLayout(MemoryStack stack, VkCommandBuffer commandBuffer, VulkanImage image, int oldLayout, int newLayout, - int sourceStage, int srcAccessMask, int destinationStage, int dstAccessMask) { - transitionLayout(stack, commandBuffer, image, 0, oldLayout, newLayout, - sourceStage, srcAccessMask, destinationStage, dstAccessMask); + public static void transitionLayout(MemoryStack stack, VkCommandBuffer commandBuffer, VulkanImage image, int oldLayout, int newLayout, int sourceStage, int srcAccessMask, int destinationStage, int dstAccessMask) { + try (java.lang.foreign.Arena arena = java.lang.foreign.Arena.ofConfined()) { + transitionLayout(arena, commandBuffer, image, 0, oldLayout, newLayout, sourceStage, srcAccessMask, destinationStage, dstAccessMask); + } } - public static void transitionLayout(MemoryStack stack, VkCommandBuffer commandBuffer, VulkanImage image, int baseLevel, int oldLayout, int newLayout, - int sourceStage, int srcAccessMask, int destinationStage, int dstAccessMask) { + public static void transitionLayout(MemoryStack stack, VkCommandBuffer commandBuffer, VulkanImage image, int baseLevel, int oldLayout, int newLayout, int sourceStage, int srcAccessMask, int destinationStage, int dstAccessMask) { + try (java.lang.foreign.Arena arena = java.lang.foreign.Arena.ofConfined()) { + transitionLayout(arena, commandBuffer, image, baseLevel, oldLayout, newLayout, sourceStage, srcAccessMask, destinationStage, dstAccessMask); + } + } + + public static void transitionLayout(java.lang.foreign.Arena arena, VkCommandBuffer commandBuffer, VulkanImage image, int oldLayout, int newLayout, int sourceStage, int srcAccessMask, int destinationStage, int dstAccessMask) { + transitionLayout(arena, commandBuffer, image, 0, oldLayout, newLayout, sourceStage, srcAccessMask, destinationStage, dstAccessMask); + } - VkImageMemoryBarrier.Buffer barrier = VkImageMemoryBarrier.calloc(1, stack); + public static void transitionLayout(java.lang.foreign.Arena arena, VkCommandBuffer commandBuffer, VulkanImage image, int baseLevel, int oldLayout, int newLayout, int sourceStage, int srcAccessMask, int destinationStage, int dstAccessMask) { + + long barrierAddr = arena.allocate(VkImageMemoryBarrier.SIZEOF, VkImageMemoryBarrier.ALIGNOF).address(); + VkImageMemoryBarrier.Buffer barrier = VkImageMemoryBarrier.create(barrierAddr, 1); barrier.sType(VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER); barrier.oldLayout(image.currentLayout); barrier.newLayout(newLayout); @@ -376,12 +276,7 @@ public static void transitionLayout(MemoryStack stack, VkCommandBuffer commandBu barrier.srcAccessMask(srcAccessMask); barrier.dstAccessMask(dstAccessMask); - vkCmdPipelineBarrier(commandBuffer, - sourceStage, destinationStage, - 0, - null, - null, - barrier); + vkCmdPipelineBarrier(commandBuffer, sourceStage, destinationStage, 0, null, null, barrier); image.currentLayout = newLayout; } @@ -390,21 +285,117 @@ private static boolean hasStencilComponent(int format) { return format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT; } + public static Builder builder(int width, int height) { + return new Builder(width, height); + } + + private void createImage() { + try (MemoryStack stack = stackPush()) { + LongBuffer pTextureImage = stack.mallocLong(1); + PointerBuffer pAllocation = stack.pointers(0L); + + MemoryManager.getInstance().createImage(width, height, mipLevels, format, VK_IMAGE_TILING_OPTIMAL, usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, pTextureImage, pAllocation); + + id = pTextureImage.get(0); + allocation = pAllocation.get(0); + + MemoryManager.addImage(this); + + if (this.name != null) { + Vulkan.setDebugLabel(stack, VK_OBJECT_TYPE_IMAGE, pTextureImage.get(), this.name); + } + } + } + + public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffset, int yOffset, int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, ByteBuffer buffer) { + this.uploadSubTextureAsync(mipLevel, width, height, xOffset, yOffset, unpackSkipRows, unpackSkipPixels, unpackRowLength, MemoryUtil.memAddress(buffer)); + } + + public void uploadSubTextureAsync(int mipLevel, int width, int height, int xOffset, int yOffset, int unpackSkipRows, int unpackSkipPixels, int unpackRowLength, long srcPtr) { + long uploadSize = (long) (unpackRowLength * height - unpackSkipPixels) * this.formatSize; + + StagingBuffer stagingBuffer = Vulkan.getStagingBuffer(); + + // Use a temporary staging buffer if the upload size is greater than + // the default staging buffer + if (uploadSize > stagingBuffer.getBufferSize()) { + stagingBuffer = new StagingBuffer(uploadSize); + stagingBuffer.scheduleFree(); + } + + srcPtr += ((long) unpackRowLength * unpackSkipRows + unpackSkipPixels) * this.formatSize; + + stagingBuffer.align(this.formatSize); + stagingBuffer.copyBuffer((int) uploadSize, srcPtr); + + long bufferId = stagingBuffer.getId(); + + VkCommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer().getHandle(); + try (MemoryStack stack = stackPush()) { + transferDstLayout(stack, commandBuffer); + + final int srcOffset = (int) (stagingBuffer.getOffset()); + + ImageUtil.copyBufferToImageCmd(stack, commandBuffer, bufferId, this.id, mipLevel, width, height, xOffset, yOffset, srcOffset, unpackRowLength, height); + } + } + + private void transferDstLayout(MemoryStack stack, VkCommandBuffer commandBuffer) { + transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + } + + public void readOnlyLayout() { + if (this.currentLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) return; + + try (MemoryStack stack = MemoryStack.stackPush()) { + if (Renderer.getInstance().getBoundRenderPass() != null) { + CommandPool.CommandBuffer commandBuffer = ImageUploadHelper.INSTANCE.getOrStartCommandBuffer(); + VkCommandBuffer vkCommandBuffer = commandBuffer.getHandle(); + + readOnlyLayout(stack, vkCommandBuffer); + } else { + readOnlyLayout(stack, Renderer.getCommandBuffer()); + } + } + } + + public void readOnlyLayout(MemoryStack stack, VkCommandBuffer commandBuffer) { + transitionImageLayout(stack, commandBuffer, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + } + + public void updateTextureSampler(boolean blur, boolean clamp, boolean mipmaps) { + byte flags = blur ? LINEAR_FILTERING_BIT : 0; + flags |= clamp ? CLAMP_BIT : 0; + flags |= (byte) (mipmaps ? USE_MIPMAPS_BIT | MIPMAP_LINEAR_FILTERING_BIT : 0); + + this.updateTextureSampler(flags); + } + + public void updateTextureSampler(byte flags) { + updateTextureSampler(this.mipLevels - 1, flags); + } + + public void updateTextureSampler(int maxLod, byte flags) { + this.sampler = SamplerManager.getTextureSampler((byte) maxLod, flags); + } + + public void transitionImageLayout(MemoryStack stack, VkCommandBuffer commandBuffer, int newLayout) { + transitionImageLayout(stack, commandBuffer, this, newLayout); + } + public void free() { MemoryManager.getInstance().addToFreeable(this); } public void doFree() { - if (this.id == 0L) - return; + if (this.id == 0L) return; MemoryManager.freeImage(this.id, this.allocation); vkDestroyImageView(Vulkan.getVkDevice(), this.mainImageView, null); if (this.levelImageViews != null) - Arrays.stream(this.levelImageViews).forEach( - imageView -> vkDestroyImageView(Vulkan.getVkDevice(), this.mainImageView, null)); + Arrays.stream(this.levelImageViews).forEach(imageView -> vkDestroyImageView(Vulkan.getVkDevice(), this.mainImageView, null)); this.id = 0L; } @@ -441,10 +432,6 @@ public long getSampler() { return sampler; } - public static Builder builder(int width, int height) { - return new Builder(width, height); - } - public static class Builder { final int width; final int height; @@ -464,6 +451,17 @@ public Builder(int width, int height) { this.height = height; } + private static int formatSize(int format) { + return switch (format) { + case VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_D32_SFLOAT, + VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_SINT -> 4; + case VK_FORMAT_R8_UNORM -> 1; + + default -> throw new IllegalArgumentException(String.format("Unxepcted format: %s", format)); +// default -> 0; + }; + } + public Builder setName(String name) { this.name = name; return this; @@ -477,8 +475,7 @@ public Builder setFormat(int format) { public Builder setMipLevels(int n) { this.mipLevels = (byte) n; - if (n > 1) - this.samplerFlags |= USE_MIPMAPS_BIT | MIPMAP_LINEAR_FILTERING_BIT; + if (n > 1) this.samplerFlags |= USE_MIPMAPS_BIT | MIPMAP_LINEAR_FILTERING_BIT; return this; } @@ -518,17 +515,5 @@ public VulkanImage createVulkanImage() { return VulkanImage.createTextureImage(this); } - - private static int formatSize(int format) { - return switch (format) { - case VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_SRGB, - VK_FORMAT_D32_SFLOAT, VK_FORMAT_D24_UNORM_S8_UINT, - VK_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_SINT -> 4; - case VK_FORMAT_R8_UNORM -> 1; - - default -> throw new IllegalArgumentException(String.format("Unxepcted format: %s", format)); -// default -> 0; - }; - } } } diff --git a/src/main/java/net/vulkanmod/vulkan/util/ColorUtil.java b/src/main/java/net/vulkanmod/vulkan/util/ColorUtil.java index 0c2c0990b..5c44dfa8e 100644 --- a/src/main/java/net/vulkanmod/vulkan/util/ColorUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/util/ColorUtil.java @@ -13,13 +13,61 @@ public static void useGammaCorrection(boolean b) { } public static int floatToInt(float f) { - return (int)(f * 255.0f) & 0xFF; + return (int) (f * 255.0f) & 0xFF; } public static float unpackColor(int c, int s) { return ((c >> s) & 0xFF) * COLOR_INV; } + public static int BGRAtoRGBA(int v) { + byte r = (byte) (v >> 16); + byte b = (byte) (v); + return r & 0xFF | (b << 16) & 0xFF0000 | v & 0xFF00FF00; + } + + public static float gamma(float f) { + return (float) Math.pow(f, 2.2); + } + + public static void setRGBA_Buffer(MappedBuffer buffer, float r, float g, float b, float a) { + colorConsumer.setRGBA_Buffer(buffer, r, g, b, a); + } + + public static void setRGBA_Buffer(FloatBuffer buffer, float r, float g, float b, float a) { + colorConsumer.setRGBA_Buffer(buffer, r, g, b, a); + } + + interface ColorConsumer { + + void setRGBA_Buffer(MappedBuffer buffer, float r, float g, float b, float a); + + void setRGBA_Buffer(FloatBuffer buffer, float r, float g, float b, float a); + + void setRGBA_Buffer(ByteBuffer buffer, float r, float g, float b, float a); + + default void putColor(MappedBuffer buffer, float r, float g, float b, float a) { + buffer.putFloat(0, r); + buffer.putFloat(4, g); + buffer.putFloat(8, b); + buffer.putFloat(12, a); + } + + default void putColor(FloatBuffer buffer, float r, float g, float b, float a) { + buffer.put(0, r); + buffer.put(1, g); + buffer.put(2, b); + buffer.put(3, a); + } + + default void putColor(ByteBuffer buffer, float r, float g, float b, float a) { + buffer.putFloat(0, r); + buffer.putFloat(4, g); + buffer.putFloat(8, b); + buffer.putFloat(12, a); + } + } + public static class ARGB { public static int pack(float r, float g, float b, float a) { int color = floatToInt(a) << 24 | floatToInt(r) << 16 | floatToInt(g) << 8 | floatToInt(b); @@ -86,52 +134,6 @@ public static int fromArgb32(int i) { } } - public static int BGRAtoRGBA(int v) { - byte r = (byte) (v >> 16); - byte b = (byte) (v); - return r & 0xFF | (b << 16) & 0xFF0000 | v & 0xFF00FF00; - } - - public static float gamma(float f) { - return (float) Math.pow(f, 2.2); - } - - public static void setRGBA_Buffer(MappedBuffer buffer, float r, float g, float b, float a) { - colorConsumer.setRGBA_Buffer(buffer, r, g, b, a); - } - - public static void setRGBA_Buffer(FloatBuffer buffer, float r, float g, float b, float a) { - colorConsumer.setRGBA_Buffer(buffer, r, g, b, a); - } - - interface ColorConsumer { - - void setRGBA_Buffer(MappedBuffer buffer, float r, float g, float b, float a); - void setRGBA_Buffer(FloatBuffer buffer, float r, float g, float b, float a); - void setRGBA_Buffer(ByteBuffer buffer, float r, float g, float b, float a); - - default void putColor(MappedBuffer buffer, float r, float g, float b, float a) { - buffer.putFloat(0, r); - buffer.putFloat(4, g); - buffer.putFloat(8, b); - buffer.putFloat(12, a); - } - - default void putColor(FloatBuffer buffer, float r, float g, float b, float a) { - buffer.put(0, r); - buffer.put(1, g); - buffer.put(2, b); - buffer.put(3, a); - } - - default void putColor(ByteBuffer buffer, float r, float g, float b, float a) { - buffer.putFloat(0, r); - buffer.putFloat(4, g); - buffer.putFloat(8, b); - buffer.putFloat(12, a); - } - } - public static class DefaultColorConsumer implements ColorConsumer { @Override diff --git a/src/main/java/net/vulkanmod/vulkan/util/DrawUtil.java b/src/main/java/net/vulkanmod/vulkan/util/DrawUtil.java index b5ba52581..4f726f804 100644 --- a/src/main/java/net/vulkanmod/vulkan/util/DrawUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/util/DrawUtil.java @@ -1,16 +1,9 @@ package net.vulkanmod.vulkan.util; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.*; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.ShaderInstance; -import net.vulkanmod.interfaces.ShaderMixed; import net.vulkanmod.render.PipelineManager; import net.vulkanmod.vulkan.Renderer; import net.vulkanmod.vulkan.VRenderSystem; import net.vulkanmod.vulkan.shader.GraphicsPipeline; -import org.joml.Matrix4f; -import org.joml.Matrix4fStack; import org.lwjgl.opengl.GL11; import org.lwjgl.vulkan.VK11; import org.lwjgl.vulkan.VkCommandBuffer; @@ -18,7 +11,6 @@ public class DrawUtil { public static void blitToScreen() { -// defualtBlit(); fastBlit(); } @@ -37,34 +29,4 @@ public static void fastBlit() { VRenderSystem.enableCull(); } - - public static void defualtBlit() { - Matrix4f matrix4f = new Matrix4f().setOrtho(0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 1.0F); - RenderSystem.setProjectionMatrix(matrix4f, VertexSorting.ORTHOGRAPHIC_Z); - Matrix4fStack posestack = RenderSystem.getModelViewStack(); - posestack.pushMatrix(); - posestack.identity(); - RenderSystem.applyModelViewMatrix(); - posestack.popMatrix(); - - ShaderInstance shaderInstance = Minecraft.getInstance().gameRenderer.blitShader; -// RenderSystem.setShader(() -> shaderInstance); - - Tesselator tesselator = RenderSystem.renderThreadTesselator(); - BufferBuilder bufferBuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX); - bufferBuilder.addVertex(-1.0f, -1.0f, 0.0f).setUv(0.0F, 1.0F); - bufferBuilder.addVertex(1.0f, -1.0f, 0.0f).setUv(1.0F, 1.0F); - bufferBuilder.addVertex(1.0f, 1.0f, 0.0f).setUv(1.0F, 0.0F); - bufferBuilder.addVertex(-1.0f, 1.0f, 0.0f).setUv(0.0F, 0.0F); - var meshData = bufferBuilder.buildOrThrow(); - - MeshData.DrawState parameters = meshData.drawState(); - - Renderer renderer = Renderer.getInstance(); - - GraphicsPipeline pipeline = ((ShaderMixed)(shaderInstance)).getPipeline(); - renderer.bindGraphicsPipeline(pipeline); - renderer.uploadAndBindUBOs(pipeline); - Renderer.getDrawer().draw(meshData.vertexBuffer(), parameters.mode(), parameters.format(), parameters.vertexCount()); - } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/vulkan/util/MappedBuffer.java b/src/main/java/net/vulkanmod/vulkan/util/MappedBuffer.java index 67b0f246f..2277cfab2 100644 --- a/src/main/java/net/vulkanmod/vulkan/util/MappedBuffer.java +++ b/src/main/java/net/vulkanmod/vulkan/util/MappedBuffer.java @@ -9,9 +9,6 @@ public class MappedBuffer { public final ByteBuffer buffer; public final long ptr; - public static MappedBuffer createFromBuffer(ByteBuffer buffer) { - return new MappedBuffer(buffer, MemoryUtil.memAddress0(buffer)); - } MappedBuffer(ByteBuffer buffer, long ptr) { this.buffer = buffer; this.ptr = ptr; @@ -22,19 +19,23 @@ public MappedBuffer(int size) { this.ptr = MemoryUtil.memAddress0(this.buffer); } + public static MappedBuffer createFromBuffer(ByteBuffer buffer) { + return new MappedBuffer(buffer, MemoryUtil.memAddress0(buffer)); + } + public void putFloat(int idx, float f) { - VUtil.UNSAFE.putFloat(ptr + idx, f); + VUtil.putFloat(ptr + idx, f); } public void putInt(int idx, int f) { - VUtil.UNSAFE.putInt(ptr + idx, f); + VUtil.putInt(ptr + idx, f); } public float getFloat(int idx) { - return VUtil.UNSAFE.getFloat(ptr + idx); + return VUtil.getFloat(ptr + idx); } public int getInt(int idx) { - return VUtil.UNSAFE.getInt(ptr + idx); + return VUtil.getInt(ptr + idx); } } diff --git a/src/main/java/net/vulkanmod/vulkan/util/Pair.java b/src/main/java/net/vulkanmod/vulkan/util/Pair.java index 3b05f1425..a90724d67 100644 --- a/src/main/java/net/vulkanmod/vulkan/util/Pair.java +++ b/src/main/java/net/vulkanmod/vulkan/util/Pair.java @@ -1,6 +1,6 @@ package net.vulkanmod.vulkan.util; -public class Pair { +public class Pair { public A first; public B second; @@ -8,4 +8,4 @@ public Pair(A a, B b) { this.first = a; this.second = b; } -} +} \ No newline at end of file diff --git a/src/main/java/net/vulkanmod/vulkan/util/VUtil.java b/src/main/java/net/vulkanmod/vulkan/util/VUtil.java index ab359b71a..f99b9cb77 100644 --- a/src/main/java/net/vulkanmod/vulkan/util/VUtil.java +++ b/src/main/java/net/vulkanmod/vulkan/util/VUtil.java @@ -4,11 +4,17 @@ import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryUtil; -import sun.misc.Unsafe; -import java.lang.reflect.Field; +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.nio.LongBuffer; +import java.nio.charset.StandardCharsets; import java.util.Collection; +import java.util.function.BiFunction; +import java.util.function.LongFunction; import static org.lwjgl.system.MemoryStack.stackGet; @@ -18,18 +24,25 @@ public class VUtil { public static final int UINT32_MAX = 0xFFFFFFFF; public static final long UINT64_MAX = 0xFFFFFFFFFFFFFFFFL; - public static final Unsafe UNSAFE; + // Safe memory access methods using FFM (Foreign Function & Memory API) + public static void putFloat(long address, float value) { + MemorySegment.ofAddress(address).set(ValueLayout.JAVA_FLOAT, 0, value); + } - static { - Field f = null; - try { - f = Unsafe.class.getDeclaredField("theUnsafe"); - f.setAccessible(true); - UNSAFE = (Unsafe) f.get(null); + public static void putInt(long address, int value) { + MemorySegment.ofAddress(address).set(ValueLayout.JAVA_INT, 0, value); + } - } catch (NoSuchFieldException | IllegalAccessException e) { - throw new RuntimeException(e); - } + public static void putLong(long address, long value) { + MemorySegment.ofAddress(address).set(ValueLayout.JAVA_LONG, 0, value); + } + + public static float getFloat(long address) { + return MemorySegment.ofAddress(address).get(ValueLayout.JAVA_FLOAT, 0); + } + + public static int getInt(long address) { + return MemorySegment.ofAddress(address).get(ValueLayout.JAVA_INT, 0); } public static PointerBuffer asPointerBuffer(Collection collection) { @@ -38,15 +51,15 @@ public static PointerBuffer asPointerBuffer(Collection collection) { PointerBuffer buffer = stack.mallocPointer(collection.size()); - collection.stream() - .map(stack::UTF8) - .forEach(buffer::put); + collection.stream().map(stack::UTF8).forEach(buffer::put); return buffer.rewind(); } public static void memcpy(ByteBuffer src, long dstPtr) { - MemoryUtil.memCopy(MemoryUtil.memAddress0(src), dstPtr, src.capacity()); + MemorySegment srcSegment = MemorySegment.ofBuffer(src); + MemorySegment dstSegment = MemorySegment.ofAddress(dstPtr).reinterpret(src.capacity()); + dstSegment.copyFrom(srcSegment); } public static void memcpy(ByteBuffer src, Buffer dst, long size) { @@ -56,10 +69,10 @@ public static void memcpy(ByteBuffer src, Buffer dst, long size) { } } - final long srcPtr = MemoryUtil.memAddress(src); final long dstPtr = dst.getDataPtr() + dst.getUsedBytes(); - - MemoryUtil.memCopy(srcPtr, dstPtr, size); + MemorySegment srcSegment = MemorySegment.ofBuffer(src).asSlice(0, size); + MemorySegment dstSegment = MemorySegment.ofAddress(dstPtr).reinterpret(size); + dstSegment.copyFrom(srcSegment); } public static void memcpy(Buffer src, ByteBuffer dst, long size) { @@ -70,9 +83,9 @@ public static void memcpy(Buffer src, ByteBuffer dst, long size) { } final long srcPtr = src.getDataPtr(); - final long dstPtr = MemoryUtil.memAddress(dst); - - MemoryUtil.memCopy(srcPtr, dstPtr, size); + MemorySegment srcSegment = MemorySegment.ofAddress(srcPtr).reinterpret(size); + MemorySegment dstSegment = MemorySegment.ofBuffer(dst).asSlice(0, size); + dstSegment.copyFrom(srcSegment); } public static void memcpy(ByteBuffer src, Buffer dst, long size, long srcOffset, long dstOffset) { @@ -83,8 +96,62 @@ public static void memcpy(ByteBuffer src, Buffer dst, long size, long srcOffset, } final long dstPtr = dst.getDataPtr() + dstOffset; - final long srcPtr = MemoryUtil.memAddress(src) + srcOffset; - MemoryUtil.memCopy(srcPtr, dstPtr, size); + + // Get source address from ByteBuffer using FFM + MemorySegment srcBuffer = MemorySegment.ofBuffer(src); + MemorySegment srcSegment = srcBuffer.asSlice(srcOffset, size); + MemorySegment dstSegment = MemorySegment.ofAddress(dstPtr).reinterpret(size); + dstSegment.copyFrom(srcSegment); + } + + public static ByteBuffer allocateByteBuffer(Arena arena, long bytes, long alignment) { + return arena.allocate(bytes, alignment).asByteBuffer(); + } + + public static LongBuffer allocateLongBuffer(Arena arena, int elements) { + MemorySegment segment = arena.allocate((long) elements * Long.BYTES, Long.BYTES); + return segment.asByteBuffer().asLongBuffer(); + } + + public static IntBuffer allocateIntBuffer(Arena arena, int elements) { + MemorySegment segment = arena.allocate((long) elements * Integer.BYTES, Integer.BYTES); + return segment.asByteBuffer().asIntBuffer(); + } + + public static LongBuffer longBuffer(Arena arena, long... values) { + MemorySegment segment = arena.allocate((long) values.length * Long.BYTES, Long.BYTES); + for (int i = 0; i < values.length; i++) { + segment.setAtIndex(ValueLayout.JAVA_LONG, i, values[i]); + } + return segment.asByteBuffer().asLongBuffer(); + } + + public static IntBuffer intBuffer(Arena arena, int... values) { + MemorySegment segment = arena.allocate((long) values.length * Integer.BYTES, Integer.BYTES); + for (int i = 0; i < values.length; i++) { + segment.setAtIndex(ValueLayout.JAVA_INT, i, values[i]); + } + return segment.asByteBuffer().asIntBuffer(); + } + + public static ByteBuffer utf8String(Arena arena, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + MemorySegment segment = arena.allocate(bytes.length + 1, 1); + segment.asSlice(0, bytes.length).copyFrom(MemorySegment.ofArray(bytes)); + segment.set(ValueLayout.JAVA_BYTE, bytes.length, (byte) 0); + ByteBuffer buffer = segment.asByteBuffer(); + buffer.limit(bytes.length + 1); + return buffer; + } + + public static T struct(Arena arena, int size, int alignment, LongFunction factory) { + long address = arena.allocate(size, alignment).address(); + return factory.apply(address); + } + + public static T structBuffer(Arena arena, int size, int alignment, int capacity, BiFunction factory) { + long address = arena.allocate((long) size * capacity, alignment).address(); + return factory.apply(address, capacity); } public static int align(int x, int align) { diff --git a/src/main/resources/assets/vulkanmod/lang/en_us.json b/src/main/resources/assets/vulkanmod/lang/en_us.json index 6947a8a90..f76ce1812 100644 --- a/src/main/resources/assets/vulkanmod/lang/en_us.json +++ b/src/main/resources/assets/vulkanmod/lang/en_us.json @@ -1,48 +1,35 @@ { "vulkanmod.options.unknown": "Unknown", - "vulkanmod.options.pages.video": "Video", "vulkanmod.options.pages.graphics": "Graphics", "vulkanmod.options.pages.optimizations": "Optimizations", "vulkanmod.options.pages.other": "Other", - "vulkanmod.options.buttons.apply": "Apply", "vulkanmod.options.buttons.kofi": "Support me", - "vulkanmod.options.advCulling": "Advanced Chunk Culling", "vulkanmod.options.advCulling.aggressive": "Aggressive", "vulkanmod.options.advCulling.conservative": "Conservative", "vulkanmod.options.advCulling.normal": "Normal", "vulkanmod.options.advCulling.tooltip": "Use a culling algorithm that might improve performance by reducing the number of non visible chunk sections rendered.", - "vulkanmod.options.ao.subBlock": "ON (Sub-block)", "vulkanmod.options.ao.subBlock.tooltip": "ON (Sub-block): Enables smooth lighting for non full block (experimental).", - "vulkanmod.options.deviceSelector": "Device selector", "vulkanmod.options.deviceSelector.auto": "Auto", "vulkanmod.options.deviceSelector.tooltip": "Current device", - "vulkanmod.options.entityCulling": "Entity Culling", "vulkanmod.options.entityCulling.tooltip": "Enables culling for entities on not visible sections.", - "vulkanmod.options.frameQueue": "Render queue size", "vulkanmod.options.frameQueue.tooltip": "Higher values might help stabilize frametime but will increase input lag.", - "vulkanmod.options.backfaceCulling": "Backface Culling", "vulkanmod.options.backfaceCulling.tooltip": "Culls not visible block faces on the CPU improving GPU performance. To prevent increased CPU overhead enable Indirect Draw.", - "vulkanmod.options.indirectDraw": "Indirect Draw", "vulkanmod.options.indirectDraw.tooltip": "Reduces CPU overhead but might increases GPU overhead.", - "vulkanmod.options.refreshRate": "Refresh Rate", - "vulkanmod.options.uniqueOpaqueLayer": "Unique opaque layer", "vulkanmod.options.uniqueOpaqueLayer.tooltip": "Use a unique render layer for opaque terrain to improve performance.", - "vulkanmod.options.windowMode": "Window Mode", "vulkanmod.options.windowMode.windowed": "Windowed", "vulkanmod.options.windowMode.windowedFullscreen": "Windowed Fullscreen", - "vulkanmod.options.builderThreads": "Chunk Builder Threads", "vulkanmod.options.builderThreads.auto": "Auto" } \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/blit/blit.json b/src/main/resources/assets/vulkanmod/shaders/basic/blit/blit.json index e38eab206..73370f0ba 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/blit/blit.json +++ b/src/main/resources/assets/vulkanmod/shaders/basic/blit/blit.json @@ -1,5 +1,7 @@ { - "samplers": [ - { "name": "Sampler0" } - ] + "samplers": [ + { + "name": "Sampler0" + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.json b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.json index ccfee165a..25d140d03 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.json +++ b/src/main/resources/assets/vulkanmod/shaders/basic/clouds/clouds.json @@ -1,17 +1,90 @@ { - "vertex": "clouds", - "fragment": "clouds", - "samplers": [], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ModelOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + "vertex": "clouds", + "fragment": "clouds", + "samplers": [], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ModelOffset", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json index b527c5169..61ed45810 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain/terrain.json @@ -1,22 +1,96 @@ { - "vertex": "terrain", - "fragment": "terrain", - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "AlphaCutout", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ], - "PushConstants": [ - { "name": "ModelOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } - ] + "vertex": "terrain", + "fragment": "terrain", + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler2" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "AlphaCutout", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ], + "PushConstants": [ + { + "name": "ModelOffset", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json index 13062973c..d845f2e43 100644 --- a/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json +++ b/src/main/resources/assets/vulkanmod/shaders/basic/terrain_earlyZ/terrain_earlyZ.json @@ -1,22 +1,96 @@ { - "vertex": "terrain", - "fragment": "terrain_earlyZ", - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "AlphaCutout", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ], - "PushConstants": [ - { "name": "ModelOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } - ] + "vertex": "terrain", + "fragment": "terrain_earlyZ", + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler2" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "AlphaCutout", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ], + "PushConstants": [ + { + "name": "ModelOffset", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.json b/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.json index 6405ec09d..1a198025f 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/blit_screen/blit_screen.json @@ -1,9 +1,11 @@ { - "vertex": "blit_screen", - "fragment": "blit_screen", - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - ] + "vertex": "blit_screen", + "fragment": "blit_screen", + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + ] } \ No newline at end of file diff --git a/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.json b/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.json index 5efc51dac..0ad9f5521 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/lightmap/lightmap.json @@ -1,30 +1,160 @@ { - "vertex": "blit_screen", - "fragment": "lightmap", - "samplers": [ - ], - "uniforms": [ - { "name": "AmbientLightFactor", "type": "float", "count": 1, "values": [1.0] }, - { "name": "SkyFactor", "type": "float", "count": 1, "values": [1.0] }, - { "name": "BlockFactor", "type": "float", "count": 1, "values": [1.0] }, - { "name": "UseBrightLightmap", "type": "int", "count": 1, "values": [0] }, - { "name": "SkyLightColor", "type": "float", "count": 3, "values": [1.0] }, - { "name": "NightVisionFactor", "type": "float", "count": 1, "values": [0.0] }, - { "name": "DarknessScale", "type": "float", "count": 1, "values": [0.0] }, - { "name": "DarkenWorldFactor", "type": "float", "count": 1, "values": [0.0] }, - { "name": "BrightnessFactor", "type": "float", "count": 1, "values": [1.0] } - ], - "UBOs": [ - { "type": "fragment", "binding": 0, "fields": [ - { "name": "AmbientLightFactor", "type": "float", "count": 1, "values": [1.0] }, - { "name": "SkyFactor", "type": "float", "count": 1, "values": [1.0] }, - { "name": "BlockFactor", "type": "float", "count": 1, "values": [1.0] }, - { "name": "UseBrightLightmap", "type": "int", "count": 1, "values": [0] }, - { "name": "SkyLightColor", "type": "float", "count": 3, "values": [1.0] }, - { "name": "NightVisionFactor", "type": "float", "count": 1, "values": [0.0] }, - { "name": "DarknessScale", "type": "float", "count": 1, "values": [0.0] }, - { "name": "DarkenWorldFactor", "type": "float", "count": 1, "values": [0.0] }, - { "name": "BrightnessFactor", "type": "float", "count": 1, "values": [1.0] } - ] } - ] + "vertex": "blit_screen", + "fragment": "lightmap", + "samplers": [ + ], + "uniforms": [ + { + "name": "AmbientLightFactor", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "SkyFactor", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "BlockFactor", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "UseBrightLightmap", + "type": "int", + "count": 1, + "values": [ + 0 + ] + }, + { + "name": "SkyLightColor", + "type": "float", + "count": 3, + "values": [ + 1.0 + ] + }, + { + "name": "NightVisionFactor", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "DarknessScale", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "DarkenWorldFactor", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "BrightnessFactor", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "fragment", + "binding": 0, + "fields": [ + { + "name": "AmbientLightFactor", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "SkyFactor", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "BlockFactor", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "UseBrightLightmap", + "type": "int", + "count": 1, + "values": [ + 0 + ] + }, + { + "name": "SkyLightColor", + "type": "float", + "count": 3, + "values": [ + 1.0 + ] + }, + { + "name": "NightVisionFactor", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "DarknessScale", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "DarkenWorldFactor", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "BrightnessFactor", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.json b/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.json index f43398ce0..e86121da8 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/particle/particle.json @@ -1,19 +1,87 @@ { - "vertex": "particle", - "fragment": "particle", - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + "vertex": "particle", + "fragment": "particle", + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler2" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position/position.json b/src/main/resources/assets/vulkanmod/shaders/core/position/position.json index ea9c19207..69e28a829 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/position/position.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/position/position.json @@ -1,28 +1,126 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "position", + "fragment": "position", + "attributes": [], + "samplers": [], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] }, - "vertex": "position", - "fragment": "position", - "attributes": [], - "samplers": [], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.json index fd537cf88..94cc3fe48 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/position_color/position_color.json @@ -1,24 +1,74 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "position_color", + "fragment": "position_color", + "attributes": [ + "Color" + ], + "samplers": [], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] }, - "vertex": "position_color", - "fragment": "position_color", - "attributes": [ - "Color" - ], - "samplers": [], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.json index ad3eac50c..19755ed9a 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/position_color_lightmap/position_color_lightmap.json @@ -1,28 +1,80 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "position_color_lightmap", + "fragment": "position_color_lightmap", + "attributes": [ + "Position", + "Color", + "UV2" + ], + "samplers": [ + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] }, - "vertex": "position_color_lightmap", - "fragment": "position_color_lightmap", - "attributes": [ - "Position", - "Color", - "UV2" - ], - "samplers": [ - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.json index afe94f3c7..baa69476d 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/position_color_normal/position_color_normal.json @@ -1,29 +1,103 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "position_color_normal", + "fragment": "position_color_normal", + "attributes": [ + "Position", + "Color", + "Normal" + ], + "samplers": [], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] }, - "vertex": "position_color_normal", - "fragment": "position_color_normal", - "attributes": [ - "Position", - "Color", - "Normal" - ], - "samplers": [], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.json index 4d92a81a6..5385d3bd3 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex/position_color_tex.json @@ -1,28 +1,80 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "position_color_tex", + "fragment": "position_color_tex", + "attributes": [ + "Position", + "Color", + "UV0" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] }, - "vertex": "position_color_tex", - "fragment": "position_color_tex", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.json b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.json index f6b71e715..ad8c4ccf3 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/position_color_tex_lightmap/position_color_tex_lightmap.json @@ -1,28 +1,80 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "position_color_tex_lightmap", + "fragment": "position_color_tex_lightmap", + "attributes": [ + "Position", + "Color", + "UV0" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] }, - "vertex": "position_color_tex_lightmap", - "fragment": "position_color_tex_lightmap", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.json b/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.json index 9f91a8dd3..dc07b86b7 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/position_tex/position_tex.json @@ -1,27 +1,79 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "position_tex", + "fragment": "position_tex", + "attributes": [ + "Position", + "UV0" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] }, - "vertex": "position_tex", - "fragment": "position_tex", - "attributes": [ - "Position", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.json b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.json index c3bbf9faf..0e6a4ab90 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color/position_tex_color.json @@ -1,20 +1,116 @@ { - "vertex": "minecraft:core/position_tex_color", - "fragment": "minecraft:core/position_tex_color", - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + "vertex": "minecraft:core/position_tex_color", + "fragment": "minecraft:core/position_tex_color", + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ModelViewMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ProjMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.json b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.json index 067700ceb..e7b03c1b2 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/position_tex_color_normal/position_tex_color_normal.json @@ -1,34 +1,134 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "position_tex_color_normal", + "fragment": "position_tex_color_normal", + "attributes": [ + "Position", + "UV0", + "Color" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] }, - "vertex": "position_tex_color_normal", - "fragment": "position_tex_color_normal", - "attributes": [ - "Position", - "UV0", - "Color" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.json index aaf972afd..b6b3041fd 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_cutout_no_cull/rendertype_armor_cutout_no_cull.json @@ -1,41 +1,179 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_armor_cutout_no_cull", + "fragment": "rendertype_armor_cutout_no_cull", + "attributes": [ + "Position", + "Color", + "UV0", + "UV2", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" }, - "vertex": "rendertype_armor_cutout_no_cull", - "fragment": "rendertype_armor_cutout_no_cull", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.json index 9ab1295ed..9ba980b2d 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_entity_glint/rendertype_armor_entity_glint.json @@ -1,34 +1,165 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_armor_entity_glint", + "fragment": "rendertype_armor_entity_glint", + "attributes": [ + "Position", + "UV0" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] }, - "vertex": "rendertype_armor_entity_glint", - "fragment": "rendertype_armor_entity_glint", - "attributes": [ - "Position", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "TextureMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "TextureMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "GlintAlpha", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_glint/rendertype_armor_glint.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_glint/rendertype_armor_glint.json index 04bbe696c..edc6b63ae 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_glint/rendertype_armor_glint.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_glint/rendertype_armor_glint.json @@ -1,19 +1,104 @@ { - "vertex": "glint", - "fragment": "glint", - "samplers": [ - { "name": "Sampler0" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + "vertex": "glint", + "fragment": "glint", + "samplers": [ + { + "name": "Sampler0" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "TextureMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "GlintAlpha", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_translucent/rendertype_armor_translucent.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_translucent/rendertype_armor_translucent.json index f393b88b0..8aa696d31 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_translucent/rendertype_armor_translucent.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_armor_translucent/rendertype_armor_translucent.json @@ -1,29 +1,115 @@ { - "vertex": "entity", - "fragment": "entity", - "defines": { - "values": { - "ALPHA_CUTOUT": "0.1" - }, - "flags": [ - "NO_OVERLAY" - ] + "vertex": "entity", + "fragment": "entity", + "defines": { + "values": { + "ALPHA_CUTOUT": "0.1" }, - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } + "flags": [ + "NO_OVERLAY" ] + }, + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler2" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.json index 846056264..7310ad579 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_beacon_beam/rendertype_beacon_beam.json @@ -1,36 +1,180 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_beacon_beam", + "fragment": "rendertype_beacon_beam", + "attributes": [ + "Position", + "Color", + "UV0" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ProjMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] }, - "vertex": "rendertype_beacon_beam", - "fragment": "rendertype_beacon_beam", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "all", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "all", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ProjMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.json index 5f2a6453e..7c2fc2f34 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_breeze_wind/rendertype_breeze_wind.json @@ -2,20 +2,129 @@ "vertex": "rendertype_breeze_wind", "fragment": "rendertype_breeze_wind", "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } + { + "name": "Sampler0" + }, + { + "name": "Sampler2" + } ], "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "FogShape", "type": "int", "count": 1, "values": [ 0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ModelViewMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "TextureMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "FogShape", + "type": "int", + "count": 1, + "values": [ + 0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json index d36098bcf..93acc3fc0 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_clouds/rendertype_clouds.json @@ -4,25 +4,202 @@ "samplers": [ ], "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ModelOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogShape", "type": "int", "count": 1, "values": [ 0 ] } + { + "name": "ModelViewMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ProjMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ModelOffset", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogShape", + "type": "int", + "count": 1, + "values": [ + 0 + ] + } ], "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "FogShape", "type": "int", "count": 1, "values": [ 0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ModelViewMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "FogShape", + "type": "int", + "count": 1, + "values": [ + 0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.json index 52c1c7608..b18cfc114 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_crumbling/rendertype_crumbling.json @@ -1,29 +1,81 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_crumbling", + "fragment": "rendertype_crumbling", + "attributes": [ + "Position", + "Color", + "UV0", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] }, - "vertex": "rendertype_crumbling", - "fragment": "rendertype_crumbling", - "attributes": [ - "Position", - "Color", - "UV0", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json index 18d86581c..4c99ac3a8 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout/rendertype_cutout.json @@ -1,38 +1,149 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_cutout", + "fragment": "rendertype_cutout", + "attributes": [ + "Position", + "Color", + "UV0", + "UV2", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" }, - "vertex": "rendertype_cutout", - "fragment": "rendertype_cutout", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ChunkOffset", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json index 79065cfea..d20d0db4d 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_cutout_mipped/rendertype_cutout_mipped.json @@ -1,38 +1,149 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_cutout_mipped", + "fragment": "rendertype_cutout_mipped", + "attributes": [ + "Position", + "Color", + "UV0", + "UV2", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" }, - "vertex": "rendertype_cutout_mipped", - "fragment": "rendertype_cutout_mipped", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ChunkOffset", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_gateway/rendertype_end_gateway.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_gateway/rendertype_end_gateway.json index 8e6cb7d0b..03560a776 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_gateway/rendertype_end_gateway.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_gateway/rendertype_end_gateway.json @@ -1,17 +1,65 @@ { - "vertex": "rendertype_end_portal", - "fragment": "rendertype_end_portal", - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "GameTime", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "EndPortalLayers", "type": "int", "count": 1, "values": [ 15 ] } - ] } - ] + "vertex": "rendertype_end_portal", + "fragment": "rendertype_end_portal", + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler1" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "GameTime", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "EndPortalLayers", + "type": "int", + "count": 1, + "values": [ + 15 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.json index 8e6cb7d0b..03560a776 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_end_portal/rendertype_end_portal.json @@ -1,17 +1,65 @@ { - "vertex": "rendertype_end_portal", - "fragment": "rendertype_end_portal", - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "GameTime", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "EndPortalLayers", "type": "int", "count": 1, "values": [ 15 ] } - ] } - ] + "vertex": "rendertype_end_portal", + "fragment": "rendertype_end_portal", + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler1" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "GameTime", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "EndPortalLayers", + "type": "int", + "count": 1, + "values": [ + 15 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.json index a47d5e123..53f6a3ffe 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_energy_swirl/rendertype_energy_swirl.json @@ -1,34 +1,158 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_energy_swirl", + "fragment": "rendertype_energy_swirl", + "attributes": [ + "Position", + "Color", + "UV0" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "TextureMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] }, - "vertex": "rendertype_energy_swirl", - "fragment": "rendertype_energy_swirl", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "TextureMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.json index edbd117d5..bfc610286 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_alpha/rendertype_entity_alpha.json @@ -1,13 +1,40 @@ { - "vertex": "rendertype_entity_alpha", - "fragment": "rendertype_entity_alpha", - "samplers": [ - { "name": "Sampler0" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] } - - ] + "vertex": "rendertype_entity_alpha", + "fragment": "rendertype_entity_alpha", + "samplers": [ + { + "name": "Sampler0" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout/rendertype_entity_cutout.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout/rendertype_entity_cutout.json index ea44c9e1e..22576e2b7 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout/rendertype_entity_cutout.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout/rendertype_entity_cutout.json @@ -1,27 +1,115 @@ { - "vertex": "entity", - "fragment": "entity", - "defines": { - "values": { - "ALPHA_CUTOUT": "0.1" + "vertex": "entity", + "fragment": "entity", + "defines": { + "values": { + "ALPHA_CUTOUT": "0.1" + } + }, + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler1" + }, + { + "name": "Sampler2" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] } + ] }, - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json index ea44c9e1e..22576e2b7 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull/rendertype_entity_cutout_no_cull.json @@ -1,27 +1,115 @@ { - "vertex": "entity", - "fragment": "entity", - "defines": { - "values": { - "ALPHA_CUTOUT": "0.1" + "vertex": "entity", + "fragment": "entity", + "defines": { + "values": { + "ALPHA_CUTOUT": "0.1" + } + }, + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler1" + }, + { + "name": "Sampler2" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] } + ] }, - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json index ea44c9e1e..22576e2b7 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_cutout_no_cull_z_offset/rendertype_entity_cutout_no_cull_z_offset.json @@ -1,27 +1,115 @@ { - "vertex": "entity", - "fragment": "entity", - "defines": { - "values": { - "ALPHA_CUTOUT": "0.1" + "vertex": "entity", + "fragment": "entity", + "defines": { + "values": { + "ALPHA_CUTOUT": "0.1" + } + }, + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler1" + }, + { + "name": "Sampler2" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] } + ] }, - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.json index 7ff513675..860ebfb7a 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_decal/rendertype_entity_decal.json @@ -1,43 +1,183 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" - }, - "vertex": "rendertype_entity_decal", - "fragment": "rendertype_entity_decal", - "attributes": [ - "Position", - "Color", - "UV0", - "UV1", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_entity_decal", + "fragment": "rendertype_entity_decal", + "attributes": [ + "Position", + "Color", + "UV0", + "UV1", + "UV2", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler1" + }, + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.json index 669060bd4..af6f4959d 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint/rendertype_entity_glint.json @@ -1,34 +1,165 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_entity_glint", + "fragment": "rendertype_entity_glint", + "attributes": [ + "Position", + "UV0" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] }, - "vertex": "rendertype_entity_glint", - "fragment": "rendertype_entity_glint", - "attributes": [ - "Position", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "TextureMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "TextureMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "GlintAlpha", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.json index b7f6179a0..b836e5ee4 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_glint_direct/rendertype_entity_glint_direct.json @@ -1,34 +1,165 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_entity_glint_direct", + "fragment": "rendertype_entity_glint_direct", + "attributes": [ + "Position", + "UV0" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] }, - "vertex": "rendertype_entity_glint_direct", - "fragment": "rendertype_entity_glint_direct", - "attributes": [ - "Position", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "TextureMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "TextureMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "GlintAlpha", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.json index 4a9b8f495..62dc807d5 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_no_outline/rendertype_entity_no_outline.json @@ -1,41 +1,179 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_entity_no_outline", + "fragment": "rendertype_entity_no_outline", + "attributes": [ + "Position", + "Color", + "UV0", + "UV2", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" }, - "vertex": "rendertype_entity_no_outline", - "fragment": "rendertype_entity_no_outline", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.json index 96628895f..3516b64a6 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_shadow/rendertype_entity_shadow.json @@ -1,28 +1,80 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_entity_shadow", + "fragment": "rendertype_entity_shadow", + "attributes": [ + "Position", + "Color", + "UV0" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] }, - "vertex": "rendertype_entity_shadow", - "fragment": "rendertype_entity_shadow", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json index ea44c9e1e..22576e2b7 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_smooth_cutout/rendertype_entity_smooth_cutout.json @@ -1,27 +1,115 @@ { - "vertex": "entity", - "fragment": "entity", - "defines": { - "values": { - "ALPHA_CUTOUT": "0.1" + "vertex": "entity", + "fragment": "entity", + "defines": { + "values": { + "ALPHA_CUTOUT": "0.1" + } + }, + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler1" + }, + { + "name": "Sampler2" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] } + ] }, - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.json index 0e4e0177b..ba9a0150c 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_solid/rendertype_entity_solid.json @@ -1,22 +1,110 @@ { - "vertex": "rendertype_entity_solid", - "fragment": "rendertype_entity_solid", - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + "vertex": "rendertype_entity_solid", + "fragment": "rendertype_entity_solid", + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler1" + }, + { + "name": "Sampler2" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent/rendertype_entity_translucent.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent/rendertype_entity_translucent.json index ea44c9e1e..22576e2b7 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent/rendertype_entity_translucent.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent/rendertype_entity_translucent.json @@ -1,27 +1,115 @@ { - "vertex": "entity", - "fragment": "entity", - "defines": { - "values": { - "ALPHA_CUTOUT": "0.1" + "vertex": "entity", + "fragment": "entity", + "defines": { + "values": { + "ALPHA_CUTOUT": "0.1" + } + }, + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler1" + }, + { + "name": "Sampler2" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] } + ] }, - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json index 3586e725a..665858389 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_cull/rendertype_entity_translucent_cull.json @@ -1,37 +1,175 @@ { - "vertex": "rendertype_entity_translucent_cull", - "fragment": "rendertype_entity_translucent_cull", - "attributes": [ - "Position", - "Color", - "UV0", - "UV1", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + "vertex": "rendertype_entity_translucent_cull", + "fragment": "rendertype_entity_translucent_cull", + "attributes": [ + "Position", + "Color", + "UV0", + "UV1", + "UV2", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" + }, + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.json index c69e75508..9801beec4 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_entity_translucent_emissive/rendertype_entity_translucent_emissive.json @@ -1,40 +1,160 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_entity_translucent_emissive", + "fragment": "rendertype_entity_translucent_emissive", + "attributes": [ + "Position", + "Color", + "UV0", + "UV1", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" }, - "vertex": "rendertype_entity_translucent_emissive", - "fragment": "rendertype_entity_translucent_emissive", - "attributes": [ - "Position", - "Color", - "UV0", - "UV1", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler1" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "Sampler1" + }, + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.json index 57462d602..e6983c543 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_eyes/rendertype_eyes.json @@ -1,32 +1,112 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_eyes", + "fragment": "rendertype_eyes", + "attributes": [ + "Position", + "Color", + "UV0" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] }, - "vertex": "rendertype_eyes", - "fragment": "rendertype_eyes", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint/rendertype_glint.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint/rendertype_glint.json index 04bbe696c..edc6b63ae 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint/rendertype_glint.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint/rendertype_glint.json @@ -1,19 +1,104 @@ { - "vertex": "glint", - "fragment": "glint", - "samplers": [ - { "name": "Sampler0" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + "vertex": "glint", + "fragment": "glint", + "samplers": [ + { + "name": "Sampler0" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "TextureMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "GlintAlpha", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_direct/rendertype_glint_direct.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_direct/rendertype_glint_direct.json index aadaa01d4..edc6b63ae 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_direct/rendertype_glint_direct.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_direct/rendertype_glint_direct.json @@ -1,19 +1,104 @@ { - "vertex": "glint", - "fragment": "glint", - "samplers": [ - { "name": "Sampler0" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + "vertex": "glint", + "fragment": "glint", + "samplers": [ + { + "name": "Sampler0" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "TextureMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "GlintAlpha", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_translucent/rendertype_glint_translucent.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_translucent/rendertype_glint_translucent.json index aadaa01d4..edc6b63ae 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_translucent/rendertype_glint_translucent.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_glint_translucent/rendertype_glint_translucent.json @@ -1,19 +1,104 @@ { - "vertex": "glint", - "fragment": "glint", - "samplers": [ - { "name": "Sampler0" } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + "vertex": "glint", + "fragment": "glint", + "samplers": [ + { + "name": "Sampler0" + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "TextureMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "GlintAlpha", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui/rendertype_gui.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui/rendertype_gui.json index 904c1badf..ccb5b6b2e 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui/rendertype_gui.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui/rendertype_gui.json @@ -1,19 +1,113 @@ { - "vertex": "minecraft:core/gui", - "fragment": "minecraft:core/gui", - "samplers": [ - ], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + "vertex": "minecraft:core/gui", + "fragment": "minecraft:core/gui", + "samplers": [ + ], + "uniforms": [ + { + "name": "ModelViewMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ProjMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_ghost_recipe_overlay.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_ghost_recipe_overlay.json index 904c1badf..ccb5b6b2e 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_ghost_recipe_overlay.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_ghost_recipe_overlay.json @@ -1,19 +1,113 @@ { - "vertex": "minecraft:core/gui", - "fragment": "minecraft:core/gui", - "samplers": [ - ], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + "vertex": "minecraft:core/gui", + "fragment": "minecraft:core/gui", + "samplers": [ + ], + "uniforms": [ + { + "name": "ModelViewMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ProjMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_overlay/rendertype_gui_overlay.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_overlay/rendertype_gui_overlay.json index 904c1badf..ccb5b6b2e 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_overlay/rendertype_gui_overlay.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_overlay/rendertype_gui_overlay.json @@ -1,19 +1,113 @@ { - "vertex": "minecraft:core/gui", - "fragment": "minecraft:core/gui", - "samplers": [ - ], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + "vertex": "minecraft:core/gui", + "fragment": "minecraft:core/gui", + "samplers": [ + ], + "uniforms": [ + { + "name": "ModelViewMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ProjMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_text_highlight.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_text_highlight.json index 904c1badf..ccb5b6b2e 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_text_highlight.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_gui_text_highlight.json @@ -1,19 +1,113 @@ { - "vertex": "minecraft:core/gui", - "fragment": "minecraft:core/gui", - "samplers": [ - ], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + "vertex": "minecraft:core/gui", + "fragment": "minecraft:core/gui", + "samplers": [ + ], + "uniforms": [ + { + "name": "ModelViewMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ProjMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.json index 8bfd37985..592a33f04 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_item_entity_translucent_cull/rendertype_item_entity_translucent_cull.json @@ -1,41 +1,179 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_item_entity_translucent_cull", + "fragment": "rendertype_item_entity_translucent_cull", + "attributes": [ + "Position", + "Color", + "UV0", + "UV2", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" }, - "vertex": "rendertype_item_entity_translucent_cull", - "fragment": "rendertype_item_entity_translucent_cull", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, - { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "Light0_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "Light1_Direction", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.json index 373975076..29adb414f 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_leash/rendertype_leash.json @@ -1,34 +1,134 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_leash", + "fragment": "rendertype_leash", + "attributes": [ + "Position", + "Color", + "UV2" + ], + "samplers": [ + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] }, - "vertex": "rendertype_leash", - "fragment": "rendertype_leash", - "attributes": [ - "Position", - "Color", - "UV2" - ], - "samplers": [ - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.json index 59a6d6ad0..a2f36ec27 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lightning/rendertype_lightning.json @@ -1,28 +1,106 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_lightning", + "fragment": "rendertype_lightning", + "attributes": [ + "Color" + ], + "samplers": [], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] }, - "vertex": "rendertype_lightning", - "fragment": "rendertype_lightning", - "attributes": [ - "Color" - ], - "samplers": [], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.json index b719262ee..f14a5f255 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_lines/rendertype_lines.json @@ -1,36 +1,206 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_lines", + "fragment": "rendertype_lines", + "attributes": [ + "Position", + "Color", + "Normal" + ], + "samplers": [], + "uniforms": [ + { + "name": "ModelViewMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] }, - "vertex": "rendertype_lines", - "fragment": "rendertype_lines", - "attributes": [ - "Position", - "Color", - "Normal" - ], - "samplers": [], - "uniforms": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "LineWidth", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "ScreenSize", "type": "float", "count": 2, "values": [ 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ScreenSize", "type": "float", "count": 2, "values": [ 1.0, 1.0 ] }, - { "name": "LineWidth", "type": "float", "count": 1, "values": [ 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "ProjMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "LineWidth", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "ScreenSize", + "type": "float", + "count": 2, + "values": [ + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "ModelViewMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ProjMat", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ScreenSize", + "type": "float", + "count": 2, + "values": [ + 1.0, + 1.0 + ] + }, + { + "name": "LineWidth", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.json index dbb6a88db..55aba32f4 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_outline/rendertype_outline.json @@ -1,28 +1,80 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_outline", + "fragment": "rendertype_outline", + "attributes": [ + "Position", + "Color", + "UV0" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] }, - "vertex": "rendertype_outline", - "fragment": "rendertype_outline", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json index f4cd0c92d..623997234 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_solid/rendertype_solid.json @@ -1,38 +1,149 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_solid", + "fragment": "rendertype_solid", + "attributes": [ + "Position", + "Color", + "UV0", + "UV2", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" }, - "vertex": "rendertype_solid", - "fragment": "rendertype_solid", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ChunkOffset", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.json index e72c6b337..c751c5033 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text/rendertype_text.json @@ -1,36 +1,138 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_text", + "fragment": "rendertype_text", + "attributes": [ + "Position", + "Color", + "UV0", + "UV2" + ], + "samplers": [ + { + "name": "Sampler0" }, - "vertex": "rendertype_text", - "fragment": "rendertype_text", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.json index 786c39176..4879eb064 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background/rendertype_text_background.json @@ -1,35 +1,142 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_text_background", + "fragment": "rendertype_text_background", + "attributes": [ + "Position", + "Color", + "UV2" + ], + "samplers": [ + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] }, - "vertex": "rendertype_text_background", - "fragment": "rendertype_text_background", - "attributes": [ - "Position", - "Color", - "UV2" - ], - "samplers": [ - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogShape", "type": "int", "count": 1, "values": [ 0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogShape", + "type": "int", + "count": 1, + "values": [ + 0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.json index b70d3129a..e5dde3655 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_background_see_through/rendertype_text_background_see_through.json @@ -1,25 +1,75 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_text_background_see_through", + "fragment": "rendertype_text_background_see_through", + "attributes": [ + "Position", + "Color" + ], + "samplers": [], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] }, - "vertex": "rendertype_text_background_see_through", - "fragment": "rendertype_text_background_see_through", - "attributes": [ - "Position", - "Color" - ], - "samplers": [], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.json index a2bc21221..1306b6aeb 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity/rendertype_text_intensity.json @@ -1,36 +1,138 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_text_intensity", + "fragment": "rendertype_text_intensity", + "attributes": [ + "Position", + "Color", + "UV0", + "UV2" + ], + "samplers": [ + { + "name": "Sampler0" }, - "vertex": "rendertype_text_intensity", - "fragment": "rendertype_text_intensity", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.json index 7c83ff3f2..93cc0a494 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_intensity_see_through/rendertype_text_intensity_see_through.json @@ -1,28 +1,80 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_text_intensity_see_through", + "fragment": "rendertype_text_intensity_see_through", + "attributes": [ + "Position", + "Color", + "UV0" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] }, - "vertex": "rendertype_text_intensity_see_through", - "fragment": "rendertype_text_intensity_see_through", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.json index 42009dce5..541fe8181 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_text_see_through/rendertype_text_see_through.json @@ -1,28 +1,80 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_text_see_through", + "fragment": "rendertype_text_see_through", + "attributes": [ + "Position", + "Color", + "UV0" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] }, - "vertex": "rendertype_text_see_through", - "fragment": "rendertype_text_see_through", - "attributes": [ - "Position", - "Color", - "UV0" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json index 19d8c6f7d..e7be632c9 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent/rendertype_translucent.json @@ -1,38 +1,149 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_translucent", + "fragment": "rendertype_translucent", + "attributes": [ + "Position", + "Color", + "UV0", + "UV2", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" }, - "vertex": "rendertype_translucent", - "fragment": "rendertype_translucent", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ChunkOffset", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.json index 00a20cbba..9bd8fc8f8 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_moving_block/rendertype_translucent_moving_block.json @@ -1,31 +1,85 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_translucent_moving_block", + "fragment": "rendertype_translucent_moving_block", + "attributes": [ + "Position", + "Color", + "UV0", + "UV2", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" }, - "vertex": "rendertype_translucent_moving_block", - "fragment": "rendertype_translucent_moving_block", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.json index 072428c98..2e9117df3 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_translucent_no_crumbling/rendertype_translucent_no_crumbling.json @@ -1,29 +1,81 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_translucent_no_crumbling", + "fragment": "rendertype_translucent_no_crumbling", + "attributes": [ + "Position", + "Color", + "UV0", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] }, - "vertex": "rendertype_translucent_no_crumbling", - "fragment": "rendertype_translucent_no_crumbling", - "attributes": [ - "Position", - "Color", - "UV0", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json index 6a5d92cce..8c4f9f629 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_tripwire/rendertype_tripwire.json @@ -1,38 +1,149 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_tripwire", + "fragment": "rendertype_tripwire", + "attributes": [ + "Position", + "Color", + "UV0", + "UV2", + "Normal" + ], + "samplers": [ + { + "name": "Sampler0" }, - "vertex": "rendertype_tripwire", - "fragment": "rendertype_tripwire", - "attributes": [ - "Position", - "Color", - "UV0", - "UV2", - "Normal" - ], - "samplers": [ - { "name": "Sampler0" }, - { "name": "Sampler2" } - ], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, - { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, - { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] }, - { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, - { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] } - ] } - ] + { + "name": "Sampler2" + } + ], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "name": "ChunkOffset", + "type": "float", + "count": 3, + "values": [ + 0.0, + 0.0, + 0.0 + ] + } + ] + }, + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "name": "FogColor", + "type": "float", + "count": 4, + "values": [ + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "name": "FogStart", + "type": "float", + "count": 1, + "values": [ + 0.0 + ] + }, + { + "name": "FogEnd", + "type": "float", + "count": 1, + "values": [ + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.json b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.json index 52f69c0bb..da937211c 100644 --- a/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.json +++ b/src/main/resources/assets/vulkanmod/shaders/core/rendertype_water_mask/rendertype_water_mask.json @@ -1,22 +1,72 @@ { - "blend": { - "func": "add", - "srcrgb": "srcalpha", - "dstrgb": "1-srcalpha" + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_water_mask", + "fragment": "rendertype_water_mask", + "attributes": [], + "samplers": [], + "uniforms": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ], + "UBOs": [ + { + "type": "vertex", + "binding": 0, + "fields": [ + { + "name": "MVP", + "type": "matrix4x4", + "count": 16, + "values": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + } + ] }, - "vertex": "rendertype_water_mask", - "fragment": "rendertype_water_mask", - "attributes": [], - "samplers": [], - "uniforms": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ], - "UBOs": [ - { "type": "vertex", "binding": 0, "fields": [ - { "name": "MVP", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] } - ] }, - { "type": "fragment", "binding": 1, "fields": [ - { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] } - ] } - ] + { + "type": "fragment", + "binding": 1, + "fields": [ + { + "name": "ColorModulator", + "type": "float", + "count": 4, + "values": [ + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + ] + } + ] } diff --git a/src/main/resources/assets/vulkanmod/shaders/raytracing/closesthit.rchit b/src/main/resources/assets/vulkanmod/shaders/raytracing/closesthit.rchit new file mode 100644 index 000000000..bd511d26f --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/raytracing/closesthit.rchit @@ -0,0 +1,9 @@ +#version 460 +#extension GL_EXT_ray_tracing : require + +layout(location = 0) rayPayloadInEXT vec3 hitValue; +hitAttributeEXT vec2 attribs; + +void main() { + hitValue = vec3(1.0, 1.0, 1.0); +} diff --git a/src/main/resources/assets/vulkanmod/shaders/raytracing/miss.rmiss b/src/main/resources/assets/vulkanmod/shaders/raytracing/miss.rmiss new file mode 100644 index 000000000..14c93a381 --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/raytracing/miss.rmiss @@ -0,0 +1,8 @@ +#version 460 +#extension GL_EXT_ray_tracing : require + +layout(location = 0) rayPayloadInEXT vec3 hitValue; + +void main() { + hitValue = vec3(0.0, 0.0, 0.0); +} diff --git a/src/main/resources/assets/vulkanmod/shaders/raytracing/raygen.rgen b/src/main/resources/assets/vulkanmod/shaders/raytracing/raygen.rgen new file mode 100644 index 000000000..443d8e3cf --- /dev/null +++ b/src/main/resources/assets/vulkanmod/shaders/raytracing/raygen.rgen @@ -0,0 +1,8 @@ +#version 460 +#extension GL_EXT_ray_tracing : require + +layout(location = 0) rayPayloadEXT vec3 hitValue; + +void main() { + hitValue = vec3(0.0, 0.0, 0.0); +} diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index b70e87d78..1315ce1d9 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -2,7 +2,6 @@ "schemaVersion": 1, "id": "vulkanmod", "version": "${version}", - "name": "VulkanMod", "description": "Bring Vulkan to Minecraft!", "authors": [ @@ -12,9 +11,7 @@ "homepage": "", "sources": "https://github.com/xCollateral/VulkanMod" }, - "icon": "assets/vulkanmod/Vlogo.png", - "environment": "client", "entrypoints": { "client": [ @@ -24,11 +21,14 @@ "mixins": [ "vulkanmod.mixins.json" ], - "accessWidener" : "vulkanmod.accesswidener", - + "accessWidener": "vulkanmod.accesswidener", "depends": { "fabricloader": ">=0.14.14", - "minecraft": ["1.21", "1.21.1"] + "minecraft": [ + "1.21", + "1.21.1", + "1.21.10" + ] }, "custom": { "fabric-renderer-api-v1:contains_renderer": true diff --git a/src/main/resources/vulkanmod.accesswidener b/src/main/resources/vulkanmod.accesswidener index 2dd84a08c..a8492e9da 100644 --- a/src/main/resources/vulkanmod.accesswidener +++ b/src/main/resources/vulkanmod.accesswidener @@ -12,6 +12,4 @@ accessible class net/minecraft/client/renderer/texture/SpriteContents$AnimatedTe accessible field net/minecraft/client/renderer/texture/SpriteContents$AnimatedTexture frames Ljava/util/List; accessible field net/minecraft/client/renderer/texture/SpriteContents$FrameInfo time I -#1.20 -accessible field com/mojang/blaze3d/systems/RenderSystem vertexSorting Lcom/mojang/blaze3d/vertex/VertexSorting; accessible field net/minecraft/client/renderer/RenderStateShard name Ljava/lang/String; diff --git a/src/main/resources/vulkanmod.mixins.json b/src/main/resources/vulkanmod.mixins.json index 7ada95708..33a2cdb76 100644 --- a/src/main/resources/vulkanmod.mixins.json +++ b/src/main/resources/vulkanmod.mixins.json @@ -4,8 +4,7 @@ "package": "net.vulkanmod.mixin", "compatibilityLevel": "JAVA_17", "plugin": "net.vulkanmod.mixin.MixinPlugin", - "mixins": [ - ], + "mixins": [], "client": [ "chunk.ClientChunkCacheM", "chunk.ClientPacketListenerM", @@ -13,69 +12,48 @@ "chunk.FrustumMixin", "chunk.LevelRendererMixin", "chunk.SectionBufferBuilderPoolM", - "chunk.SectionRenderDispatcherM", "chunk.ViewAreaM", "chunk.VisibilitySetMixin", - "compatibility.EffectInstanceM", - "compatibility.PostChainM", - "compatibility.PostPassM", - "compatibility.ProgramM", - "compatibility.UniformM", "compatibility.gl.GL11M", "compatibility.gl.GL15M", "compatibility.gl.GL30M", "debug.DebugScreenOverlayM", - "debug.GlDebugInfoM", "debug.KeyboardHandlerM", "debug.crash_report.SystemReportM", "matrix.Matrix4fM", "matrix.PoseAccessor", - "profiling.ClientMetricsSamplersProviderMixin", "profiling.GuiMixin", "profiling.KeyboardHandlerM", "profiling.LevelRendererMixin", - "render.BufferUploaderM", - "render.GameRendererMixin", - "render.GlProgramManagerMixin", + "render.DirectStateAccessCoreMixin", + "render.DirectStateAccessEmulatedMixin", + "render.FogRendererMixin", + "render.GlDeviceMixin", + "render.GlProgramMixin", + "render.GlShaderModuleMixin", "render.GlStateManagerM", "render.MinecraftMixin", "render.RenderSystemMixin", "render.RenderTypeM", - "render.ShaderInstanceM", "render.biome.BiomeManagerM", "render.block.BakedQuadM", "render.clouds.LevelRendererM", "render.color.BlockColorsM", "render.entity.EntityRendererM", - "render.entity.LevelRendererM", - "render.entity.model.ModelPartCubeM", - "render.entity.model.ModelPartM", + "render.frame.FramerateLimitTrackerMixin", "render.frame.MinecraftMixin", "render.frame.RenderSystemMixin", - "render.frapi.BakedModelM", - "render.frapi.ItemRendererAccessor", - "render.frapi.ItemRendererMixin", - "render.frapi.ModelBlockRendererM", - "render.particle.SingleQuadParticleM", - "render.target.MainTargetMixin", - "render.target.RenderTargetMixin", + "render.frame.TimerQueryMixin", "render.vertex.BufferBuilderM", - "render.vertex.FaceBakeryM", "render.vertex.IndexTypeMixin", - "render.vertex.VertexBufferM", "render.vertex.VertexFormatMixin", "screen.OptionsScreenM", "screen.ScreenM", - "texture.MAbstractTexture", - "texture.MTextureUtil", - "texture.image.MNativeImage", "texture.image.NativeImageAccessor", "texture.mip.MipmapGeneratorM", "texture.update.GameRendererM", - "texture.update.MLightTexture", "texture.update.MSpriteContents", "texture.update.MTextureManager", - "util.ScreenshotRecorderM", "vertex.EntityOutlineGeneratorM", "vertex.SpriteCoordinateExpanderM", "vertex.VertexMultiConsumersM$DoubleM",