From 8401353e4dcc19509781c47ea4e1e35f34902ba1 Mon Sep 17 00:00:00 2001 From: coolGi Date: Fri, 21 Jul 2023 19:13:08 +0930 Subject: [PATCH 01/24] Another save commit for fog fix --- .../shaders/AbstractShaderRenderer.java | 11 +++++---- .../render/renderer/shaders/FogShader.java | 14 +++++++---- .../render/renderer/shaders/SSAOShader.java | 10 ++++++-- core/src/main/resources/shaders/fog/fog.frag | 23 ++++++++++--------- core/src/main/resources/shaders/fog/fog.vert | 9 +++++--- core/src/main/resources/shaders/normal.vert | 6 ++--- 6 files changed, 46 insertions(+), 27 deletions(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/AbstractShaderRenderer.java b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/AbstractShaderRenderer.java index 43b6a1704..53932bdab 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/AbstractShaderRenderer.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/AbstractShaderRenderer.java @@ -29,7 +29,7 @@ public abstract class AbstractShaderRenderer { protected final ShaderProgram shader; protected final ShaderProgram applyShader; - protected GLVertexBuffer boxBuffer; + public GLVertexBuffer boxBuffer; protected VertexAttribute va; boolean init = false; @@ -46,9 +46,8 @@ public abstract class AbstractShaderRenderer { protected AbstractShaderRenderer(ShaderProgram shader, ShaderProgram applyShader) { this.shader = shader; this.applyShader = applyShader; - - } + private void init() { if (init) return; init = true; @@ -56,7 +55,7 @@ public abstract class AbstractShaderRenderer { va = VertexAttribute.create(); va.bind(); // Pos - va.setVertexAttribute(0, 0, VertexAttribute.VertexPointer.addVec2Pointer(false)); + setVertexAttributes(); va.completeAndCheck(Float.BYTES * 2); // Some shader stuff needs to be set a bit later than @@ -65,6 +64,10 @@ public abstract class AbstractShaderRenderer { createBuffer(); } + /** Sets all the vertex attributes */ + void setVertexAttributes() { + va.setVertexAttribute(0, 0, VertexAttribute.VertexPointer.addVec2Pointer(false)); + }; /** Overwrite this to apply uniforms to the shader */ void setShaderUniforms(float partialTicks) {}; /** Overwrite this to apply uniforms to the apply shader */ diff --git a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/FogShader.java b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/FogShader.java index 87a5805f8..ef5e6f3bd 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/FogShader.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/FogShader.java @@ -6,6 +6,7 @@ import com.seibel.distanthorizons.core.dependencyInjection.SingletonInjector; import com.seibel.distanthorizons.core.render.fog.LodFogConfig; import com.seibel.distanthorizons.core.render.glObject.shader.Shader; import com.seibel.distanthorizons.core.render.glObject.shader.ShaderProgram; +import com.seibel.distanthorizons.core.render.glObject.vertexAttribute.VertexAttribute; import com.seibel.distanthorizons.core.util.LodUtil; import com.seibel.distanthorizons.core.util.RenderUtil; import com.seibel.distanthorizons.core.wrapperInterfaces.IVersionConstants; @@ -21,7 +22,7 @@ public class FogShader extends AbstractShaderRenderer { // public final int modelOffsetUniform; - public final int worldYOffsetUniform; +// public final int worldYOffsetUniform; // Fog Uniforms public final int fogColorUniform; @@ -38,11 +39,11 @@ public class FogShader extends AbstractShaderRenderer { super(new ShaderProgram( () -> Shader.loadFile("shaders/fog/fog.vert", false, new StringBuilder()).toString(), () -> fogConfig.loadAndProcessFragShader("shaders/fog/fog.frag", false).toString(), - "fragColor", new String[] { "vPosition", "vPos", "color" } + "fragColor", new String[] { "vPos", "vPosition" } )); // modelOffsetUniform = this.shader.getUniformLocation("modelOffset"); - worldYOffsetUniform = this.shader.getUniformLocation("worldYOffset"); +// worldYOffsetUniform = this.shader.tryGetUniformLocation("worldYOffset"); // Fog uniforms fogColorUniform = this.shader.getUniformLocation("fogColor"); fullFogModeUniform = this.shader.getUniformLocation("fullFogMode"); @@ -53,6 +54,11 @@ public class FogShader extends AbstractShaderRenderer { nearFogLengthUniform = this.shader.tryGetUniformLocation("nearFogLength"); } + @Override + void setVertexAttributes() { + this.va.setVertexAttribute(0, 0, VertexAttribute.VertexPointer.addVec2Pointer(false)); + this.va.setVertexAttribute(0, 1, VertexAttribute.VertexPointer.addUnsignedShortsPointer(8, false, true)); // 2+2+2+2 + }; @Override void setShaderUniforms(float partialTicks) { @@ -62,7 +68,7 @@ public class FogShader extends AbstractShaderRenderer { vanillaDrawDistance += 32; // Give it a 2 chunk boundary for near fog. - this.shader.setUniform(worldYOffsetUniform, (float) MC.getWrappedClientWorld().getMinHeight()); +// if (worldYOffsetUniform != -1) this.shader.setUniform(worldYOffsetUniform, (float) MC.getWrappedClientWorld().getMinHeight()); // Fog this.shader.setUniform(fullFogModeUniform, MC_RENDER.isFogStateSpecial() ? 1 : 0); diff --git a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/SSAOShader.java b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/SSAOShader.java index db7a18cf6..d7fb1e8d8 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/SSAOShader.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/SSAOShader.java @@ -1,6 +1,7 @@ package com.seibel.distanthorizons.core.render.renderer.shaders; import com.seibel.distanthorizons.core.render.glObject.shader.ShaderProgram; +import com.seibel.distanthorizons.core.render.glObject.vertexAttribute.VertexAttribute; import com.seibel.distanthorizons.core.util.LodUtil; import com.seibel.distanthorizons.core.util.RenderUtil; import com.seibel.distanthorizons.coreapi.util.math.Mat4f; @@ -16,9 +17,9 @@ public class SSAOShader extends AbstractShaderRenderer { public SSAOShader() { super( new ShaderProgram("shaders/normal.vert", "shaders/ssao/ao.frag", - "fragColor", new String[]{"vPos"}), + "fragColor", new String[]{"vPosition"}), new ShaderProgram("shaders/normal.vert", "shaders/ssao/apply-frag.frag", - "fragColor", new String[]{"vPos"}) + "fragColor", new String[]{"vPosition"}) ); } @@ -28,6 +29,11 @@ public class SSAOShader extends AbstractShaderRenderer { kernel = genKernel(); } + @Override + void setVertexAttributes() { + va.setVertexAttribute(0, 0, VertexAttribute.VertexPointer.addVec2Pointer(false)); + } + @Override void setShaderUniforms(float partialTicks) { Mat4f perspective = Mat4f.perspective( diff --git a/core/src/main/resources/shaders/fog/fog.frag b/core/src/main/resources/shaders/fog/fog.frag index d4a5a4653..e22281964 100644 --- a/core/src/main/resources/shaders/fog/fog.frag +++ b/core/src/main/resources/shaders/fog/fog.frag @@ -1,6 +1,7 @@ in vec3 vertexWorldPos; in float vertexYPos; +//in uvec4 vPosition; //in vec2 TexCoord; out vec4 fragColor; @@ -69,20 +70,20 @@ void main() { } // Testing -// if (fragColor.r != 6969.) { // This line is so that the compiler doesnt delete the previos code -//// fragColor = vec4( -//// mod(vertexWorldPos.x, 1), -//// mod(vertexWorldPos.y, 1), -//// mod(vertexWorldPos.z, 1), -//// 1. -//// ); + if (fragColor.r != 6969.) { // This line is so that the compiler doesnt delete the previos code + fragColor = vec4( + mod(vertexWorldPos.x, 1), + mod(vertexWorldPos.y, 1), + mod(vertexWorldPos.z, 1), + 1. + ); // fragColor = vec4( -// mod(vertexYPos, 1), -// mod(vertexYPos, 1), -// mod(vertexYPos, 1), +// mod(vPosition.x, 1), +// mod(vPosition.y, 1), +// mod(vPosition.z, 1), // 1. // ); -// } + } } diff --git a/core/src/main/resources/shaders/fog/fog.vert b/core/src/main/resources/shaders/fog/fog.vert index 463249402..0663c7a11 100644 --- a/core/src/main/resources/shaders/fog/fog.vert +++ b/core/src/main/resources/shaders/fog/fog.vert @@ -2,10 +2,10 @@ //uniform vec3 modelOffset; -uniform float worldYOffset; +//uniform float worldYOffset; +//in uvec4 vPosition; in vec2 vPos; -in uvec4 vPosition; out vec3 vertexWorldPos; out float vertexYPos; @@ -13,7 +13,10 @@ out float vertexYPos; void main() { // vertexWorldPos = vPosition.xyz + modelOffset; - vertexYPos = vPosition.y + worldYOffset; +// vertexWorldPos = vPosition.xyz; + vertexWorldPos = vec3(0.); + vertexYPos = 0.; +// vertexYPos = vPosition.y + worldYOffset; gl_Position = vec4(vPos, 1.0, 1.0); } \ No newline at end of file diff --git a/core/src/main/resources/shaders/normal.vert b/core/src/main/resources/shaders/normal.vert index 1485baf0e..fe4bfe03b 100644 --- a/core/src/main/resources/shaders/normal.vert +++ b/core/src/main/resources/shaders/normal.vert @@ -1,11 +1,11 @@ #version 150 core -in vec2 vPos; +in vec2 vPosition; out vec2 TexCoord; void main() { - gl_Position = vec4(vPos, 1.0, 1.0); - TexCoord = vPos.xy * 0.5 + 0.5; + gl_Position = vec4(vPosition, 1.0, 1.0); + TexCoord = vPosition.xy * 0.5 + 0.5; } \ No newline at end of file From c8e6a56467017a1c1e64092a9e2afb753b3d6026 Mon Sep 17 00:00:00 2001 From: coolGi Date: Fri, 21 Jul 2023 19:51:15 +0930 Subject: [PATCH 02/24] Changed noiseDropoff to an int, and changed the order of noise and fog --- .../client/IDhApiNoiseTextureConfig.java | 8 +- .../client/DhApiNoiseTextureConfig.java | 4 +- .../distanthorizons/core/config/Config.java | 11 +- .../core/render/fog/LodFogConfig.java | 4 +- .../main/resources/shaders/flat_shaded.frag | 130 ++++++++++-------- 5 files changed, 84 insertions(+), 73 deletions(-) diff --git a/api/src/main/java/com/seibel/distanthorizons/api/interfaces/config/client/IDhApiNoiseTextureConfig.java b/api/src/main/java/com/seibel/distanthorizons/api/interfaces/config/client/IDhApiNoiseTextureConfig.java index fc0598b1d..bf490429d 100644 --- a/api/src/main/java/com/seibel/distanthorizons/api/interfaces/config/client/IDhApiNoiseTextureConfig.java +++ b/api/src/main/java/com/seibel/distanthorizons/api/interfaces/config/client/IDhApiNoiseTextureConfig.java @@ -40,11 +40,9 @@ public interface IDhApiNoiseTextureConfig extends IDhApiConfigGroup IDhApiConfigValue noiseIntensity(); /** - * Defines how far should the noise texture render before it fades away.

- * - * 0.0 - the noise texture will render the entire LOD render distance.
- * 3.0 - the noise texture will fade away at 1/3 of the LOD render distance. + * Defines how far should the noise texture render before it fades away. (in blocks)
+ * Set to 0 to disable noise from fading away */ - IDhApiConfigValue noiseDropoff(); + IDhApiConfigValue noiseDropoff(); } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/api/external/methods/config/client/DhApiNoiseTextureConfig.java b/core/src/main/java/com/seibel/distanthorizons/core/api/external/methods/config/client/DhApiNoiseTextureConfig.java index eff0162a2..a29637de8 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/api/external/methods/config/client/DhApiNoiseTextureConfig.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/api/external/methods/config/client/DhApiNoiseTextureConfig.java @@ -45,7 +45,7 @@ public class DhApiNoiseTextureConfig implements IDhApiNoiseTextureConfig { return new DhApiConfigValue(Config.Client.Advanced.Graphics.NoiseTextureSettings.noiseIntensity); } @Override - public IDhApiConfigValue noiseDropoff() - { return new DhApiConfigValue(Config.Client.Advanced.Graphics.NoiseTextureSettings.noiseDropoff); } + public IDhApiConfigValue noiseDropoff() + { return new DhApiConfigValue(Config.Client.Advanced.Graphics.NoiseTextureSettings.noiseDropoff); } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java b/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java index 33f325060..9376024cc 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java @@ -468,14 +468,11 @@ public class Config + "How intense should the noise should be?") .build(); - public static ConfigEntry noiseDropoff = new ConfigEntry.Builder() // TODO: Make this a float (the ClassicConfigGUI doesn't support floats) - .setMinDefaultMax(0d, 3d, null) + public static ConfigEntry noiseDropoff = new ConfigEntry.Builder() // TODO: Make this a float (the ClassicConfigGUI doesn't support floats) + .setMinDefaultMax(0, 1024, null) .comment("" - + "How far should the noise texture render before it fades away? \n" - + "\n" - + "0.0 - the noise texture will render the entire LOD render distance. \n" - + "3.0 - the noise texture will fade away at 1/3 of the LOD render distance. \n" - + "") + + "Defines how far should the noise texture render before it fades away. (in blocks) \n" + + "Set to 0 to disable noise from fading away") .build(); } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/render/fog/LodFogConfig.java b/core/src/main/java/com/seibel/distanthorizons/core/render/fog/LodFogConfig.java index 4d44bc0ba..1b606638d 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/render/fog/LodFogConfig.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/render/fog/LodFogConfig.java @@ -60,7 +60,7 @@ public class LodFogConfig public final boolean noiseEnable; public final int noiseSteps; public final float noiseIntensity; - public final float noiseDropoff; + public final int noiseDropoff; public static LodFogConfig generateFogConfig() @@ -82,7 +82,7 @@ public class LodFogConfig noiseEnable = Config.Client.Advanced.Graphics.NoiseTextureSettings.noiseEnabled.get(); noiseSteps = Config.Client.Advanced.Graphics.NoiseTextureSettings.noiseSteps.get(); noiseIntensity = Config.Client.Advanced.Graphics.NoiseTextureSettings.noiseIntensity.get().floatValue(); - noiseDropoff = Config.Client.Advanced.Graphics.NoiseTextureSettings.noiseDropoff.get().floatValue(); + noiseDropoff = Config.Client.Advanced.Graphics.NoiseTextureSettings.noiseDropoff.get(); if (fogDrawMode != EFogDrawMode.FOG_DISABLED) diff --git a/core/src/main/resources/shaders/flat_shaded.frag b/core/src/main/resources/shaders/flat_shaded.frag index 3d7632a2b..e16dc3936 100644 --- a/core/src/main/resources/shaders/flat_shaded.frag +++ b/core/src/main/resources/shaders/flat_shaded.frag @@ -6,16 +6,21 @@ in vec4 vPos; out vec4 fragColor; +// Fog uniforms uniform float fogScale; uniform float fogVerticalScale; uniform float nearFogStart; uniform float nearFogLength; uniform int fullFogMode; +// Noise uniforms uniform bool noiseEnabled; uniform int noiseSteps; uniform float noiseIntensity; -uniform float noiseDropoff; +uniform int noiseDropoff; + +// SSAO uniforms +//uniform bool ssaoEnabled; /* ========MARCO DEFINED BY RUNTIME CODE GEN========= @@ -84,20 +89,82 @@ vec3 HSV2RGB(vec3 c) { } -/** +/** * Fragment Shader - * + * * author: James Seibel * author: coolGi * version: 7-2-2023 */ void main() { - vec4 returnColor; + fragColor = vertexColor; + + // TODO: Move into its own function instead of in an if statement + if (noiseEnabled) { + // This bit of code is required to fix the vertex position problem cus of floats in the verted world position varuable + vec3 vertexNormal = normalize(cross(dFdx(vPos.xyz), dFdy(vPos.xyz))); + vec3 fixedVPos = vec3( + vPos.x - vertexNormal.x * 0.001, + vPos.y - vertexNormal.y * 0.001, + vPos.z - vertexNormal.z * 0.001 + ); + float noiseAmplification = noiseIntensity / 100; + noiseAmplification = (-1 * pow(2*((fragColor.x + fragColor.y + fragColor.z) / 3) - 1, 2) + 1) * noiseAmplification; // Lessen the effect on depending on how dark the object is, equasion for this is -(2x-1)^{2}+1 + noiseAmplification *= fragColor.w; // The effect would lessen on transparent objects + + // Random value for each position + float randomValue = rand(vec3( + quantize(fixedVPos.x, noiseSteps), + quantize(fixedVPos.y, noiseSteps), + quantize(fixedVPos.z, noiseSteps) + )) + * 2. * noiseAmplification - noiseAmplification; + + + // Modifies the color + // A value of 0 on the randomValue will result in the original color, while a value of 1 will result in a fully bright color + vec3 newCol = fragColor.rgb + (vec3(1.0) - fragColor.rgb) * randomValue; + + // Clamps it and turns it back into a vec4 + if (noiseDropoff == 0) + fragColor = vec4( + clamp(newCol.r, 0., 1.), + clamp(newCol.g, 0., 1.), + clamp(newCol.b, 0., 1.), + fragColor.w + ); + else + fragColor = mix( + vec4( + clamp(newCol.r, 0., 1.), + clamp(newCol.g, 0., 1.), + clamp(newCol.b, 0., 1.), + fragColor.w + ), fragColor, + clamp(length(vertexWorldPos) / noiseDropoff, 0., 1.) // The further away it gets, the less noise gets applied + ); + + // For testing + // if (fragColor.r != 69420.) { + // fragColor = vec4( + // mod(fixedVPos.x, 1), + // mod(fixedVPos.y, 1), + // mod(fixedVPos.z, 1), + // fragColor.w); + // } + } + +// // TODO: Move into its own function instead of in an if statement +// if (ssaoEnabled) { +// +// } + + // TODO: Move into its own function instead of in an if statement if (fullFogMode != 0) { - returnColor = vec4(fogColor.rgb, 1.0); + fragColor = vec4(fogColor.rgb, 1.0); } else { // TODO: add a white texture to support Optifine shaders //vec4 textureColor = texture(texImage, textureCoord); @@ -115,59 +182,8 @@ void main() float mixedFogThickness = clamp(mixFogThickness( nearFogThickness, farFogThickness, heightFogThickness), 0.0, 1.0); - returnColor = mix(vertexColor, vec4(fogColor.rgb, 1.0), mixedFogThickness); + fragColor = mix(fragColor, vec4(fogColor.rgb, 1.0), mixedFogThickness); } - - if (noiseEnabled) { - // This bit of code is required to fix the vertex position problem cus of floats in the verted world position varuable - vec3 vertexNormal = normalize(cross(dFdx(vPos.xyz), dFdy(vPos.xyz))); - vec3 fixedVPos = vec3( - vPos.x - vertexNormal.x * 0.001, - vPos.y - vertexNormal.y * 0.001, - vPos.z - vertexNormal.z * 0.001 - ); - - - float noiseAmplification = noiseIntensity / 100; - noiseAmplification = (-1 * pow(2*((returnColor.x + returnColor.y + returnColor.z) / 3) - 1, 2) + 1) * noiseAmplification; // Lessen the effect on depending on how dark the object is, equasion for this is -(2x-1)^{2}+1 - noiseAmplification *= returnColor.w; // The effect would lessen on transparent objects - - // Random value for each position - float randomValue = rand(vec3( - quantize(fixedVPos.x, noiseSteps), - quantize(fixedVPos.y, noiseSteps), - quantize(fixedVPos.z, noiseSteps) - )) - * 2. * noiseAmplification - noiseAmplification; - - - // Modifies the color - // A value of 0 on the randomValue will result in the original color, while a value of 1 will result in a fully bright color - vec3 newCol = returnColor.rgb + (vec3(1.0) - returnColor.rgb) * randomValue; - - // Clamps it and turns it back into a vec4 - returnColor = mix( - vec4( - clamp(newCol.r, 0., 1.), - clamp(newCol.g, 0., 1.), - clamp(newCol.b, 0., 1.), - returnColor.w - ), returnColor, - clamp(length(vertexWorldPos) * fogScale * noiseDropoff, 0., 1.) // The further away it gets, the less noise gets applied - ); - - // For testing -// if (returnColor.r != 69420.) { -// returnColor = vec4( -// mod(fixedVPos.x, 1), -// mod(fixedVPos.y, 1), -// mod(fixedVPos.z, 1), -// returnColor.w); -// } - } - - // If "w" is just set to just 1. then it would crash - fragColor = returnColor; } From a724938f7187d998a2992553420d22725c764ed4 Mon Sep 17 00:00:00 2001 From: coolGi Date: Wed, 2 Aug 2023 23:04:34 +0930 Subject: [PATCH 03/24] Shader save commit --- .../core/render/fog/LodFogConfig.java | 1 + .../core/render/renderer/LodRenderProgram.java | 6 ++++-- core/src/main/resources/shaders/flat_shaded.frag | 16 +++++----------- 3 files changed, 10 insertions(+), 13 deletions(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/render/fog/LodFogConfig.java b/core/src/main/java/com/seibel/distanthorizons/core/render/fog/LodFogConfig.java index 1b606638d..8387d7979 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/render/fog/LodFogConfig.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/render/fog/LodFogConfig.java @@ -57,6 +57,7 @@ public class LodFogConfig // TODO: Move these out of here public final int earthCurveRatio; + // Noise Values public final boolean noiseEnable; public final int noiseSteps; public final float noiseIntensity; diff --git a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java index ad7e096f4..af7594cbc 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java @@ -85,7 +85,7 @@ public class LodRenderProgram extends ShaderProgram lightMapUniform = getUniformLocation("lightMap"); - // Fog uniforms + // Fog Uniforms fullFogModeUniform = getUniformLocation("fullFogMode"); fogColorUniform = getUniformLocation("fogColor"); fogScaleUniform = tryGetUniformLocation("fogScale"); @@ -94,12 +94,13 @@ public class LodRenderProgram extends ShaderProgram nearFogStartUniform = tryGetUniformLocation("nearFogStart"); nearFogLengthUniform = tryGetUniformLocation("nearFogLength"); - // Noise uniforms + // Noise Uniforms noiseEnabledUniform = getUniformLocation("noiseEnabled"); noiseStepsUniform = getUniformLocation("noiseSteps"); noiseIntensityUniform = getUniformLocation("noiseIntensity"); noiseDropoffUniform = getUniformLocation("noiseDropoff"); + // TODO: Add better use of the LODFormat thing int vertexByteCount = LodUtil.LOD_VERTEX_FORMAT.getByteSize(); if (GLProxy.getInstance().VertexAttributeBufferBindingSupported) @@ -122,6 +123,7 @@ public class LodRenderProgram extends ShaderProgram if (earthRadiusUniform != -1) setUniform(earthRadiusUniform, /*6371KM*/ 6371000.0f / fogConfig.earthCurveRatio); + // Noise Uniforms setUniform(noiseEnabledUniform, fogConfig.noiseEnable); setUniform(noiseStepsUniform, fogConfig.noiseSteps); setUniform(noiseIntensityUniform, fogConfig.noiseIntensity); diff --git a/core/src/main/resources/shaders/flat_shaded.frag b/core/src/main/resources/shaders/flat_shaded.frag index e16dc3936..014abece5 100644 --- a/core/src/main/resources/shaders/flat_shaded.frag +++ b/core/src/main/resources/shaders/flat_shaded.frag @@ -6,22 +6,19 @@ in vec4 vPos; out vec4 fragColor; -// Fog uniforms +// Fog Uniforms uniform float fogScale; uniform float fogVerticalScale; uniform float nearFogStart; uniform float nearFogLength; uniform int fullFogMode; -// Noise uniforms +// Noise Uniforms uniform bool noiseEnabled; uniform int noiseSteps; uniform float noiseIntensity; uniform int noiseDropoff; -// SSAO uniforms -//uniform bool ssaoEnabled; - /* ========MARCO DEFINED BY RUNTIME CODE GEN========= float farFogStart; @@ -89,6 +86,7 @@ vec3 HSV2RGB(vec3 c) { } + /** * Fragment Shader * @@ -100,10 +98,11 @@ void main() { fragColor = vertexColor; + // TODO: Move into its own function instead of in an if statement if (noiseEnabled) { - // This bit of code is required to fix the vertex position problem cus of floats in the verted world position varuable vec3 vertexNormal = normalize(cross(dFdx(vPos.xyz), dFdy(vPos.xyz))); + // This bit of code is required to fix the vertex position problem cus of floats in the verted world position varuable vec3 fixedVPos = vec3( vPos.x - vertexNormal.x * 0.001, vPos.y - vertexNormal.y * 0.001, @@ -157,11 +156,6 @@ void main() // } } -// // TODO: Move into its own function instead of in an if statement -// if (ssaoEnabled) { -// -// } - // TODO: Move into its own function instead of in an if statement if (fullFogMode != 0) { fragColor = vec4(fogColor.rgb, 1.0); From 3ea55065b3522f86d57b8c7e4526e353263f9b04 Mon Sep 17 00:00:00 2001 From: coolGi Date: Wed, 2 Aug 2023 23:23:06 +0930 Subject: [PATCH 04/24] Fog shader should be working --- .../core/render/renderer/LodRenderer.java | 4 +-- .../render/renderer/shaders/FogShader.java | 24 +++++++++++--- core/src/main/resources/shaders/fog/fog.frag | 33 +++++++++++++++---- core/src/main/resources/shaders/fog/fog.vert | 22 ------------- 4 files changed, 48 insertions(+), 35 deletions(-) delete mode 100644 core/src/main/resources/shaders/fog/fog.vert diff --git a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderer.java b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderer.java index 217318e82..6f5c571a0 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderer.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderer.java @@ -252,11 +252,11 @@ public class LodRenderer bufferHandler.renderOpaque(this); if (Config.Client.Advanced.Graphics.Quality.ssao.get()) { -// SSAOShader.INSTANCE.render(partialTicks); +// SSAOShader.INSTANCE.render(partialTicks); // For some reason this looks slightly different :/ SSAORenderer.INSTANCE.render(partialTicks); } { -// FogShader.INSTANCE.render(partialTicks); + FogShader.INSTANCE.render(partialTicks); // DarkShader.INSTANCE.render(partialTicks); // A test shader to make the world darker } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/FogShader.java b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/FogShader.java index ef5e6f3bd..bc709d164 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/FogShader.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/shaders/FogShader.java @@ -24,6 +24,9 @@ public class FogShader extends AbstractShaderRenderer { // public final int modelOffsetUniform; // public final int worldYOffsetUniform; + public final int gProjUniform; + public final int gDepthMapUniform; + // Fog Uniforms public final int fogColorUniform; public final int fogScaleUniform; @@ -37,13 +40,16 @@ public class FogShader extends AbstractShaderRenderer { // This code is just a temp fix so that it looks fine for the time being // and even with the jank soloution, i cannot get it to work super(new ShaderProgram( - () -> Shader.loadFile("shaders/fog/fog.vert", false, new StringBuilder()).toString(), + () -> Shader.loadFile("shaders/normal.vert", false, new StringBuilder()).toString(), () -> fogConfig.loadAndProcessFragShader("shaders/fog/fog.frag", false).toString(), - "fragColor", new String[] { "vPos", "vPosition" } + "fragColor", new String[] { "vPosition" } )); // modelOffsetUniform = this.shader.getUniformLocation("modelOffset"); // worldYOffsetUniform = this.shader.tryGetUniformLocation("worldYOffset"); + + gProjUniform = this.shader.getUniformLocation("gProj"); + gDepthMapUniform = this.shader.getUniformLocation("gDepthMap"); // Fog uniforms fogColorUniform = this.shader.getUniformLocation("fogColor"); fullFogModeUniform = this.shader.getUniformLocation("fullFogMode"); @@ -56,8 +62,7 @@ public class FogShader extends AbstractShaderRenderer { @Override void setVertexAttributes() { - this.va.setVertexAttribute(0, 0, VertexAttribute.VertexPointer.addVec2Pointer(false)); - this.va.setVertexAttribute(0, 1, VertexAttribute.VertexPointer.addUnsignedShortsPointer(8, false, true)); // 2+2+2+2 + va.setVertexAttribute(0, 0, VertexAttribute.VertexPointer.addVec2Pointer(false)); }; @Override @@ -68,8 +73,19 @@ public class FogShader extends AbstractShaderRenderer { vanillaDrawDistance += 32; // Give it a 2 chunk boundary for near fog. + Mat4f perspective = Mat4f.perspective( + (float) MC_RENDER.getFov(partialTicks), + MC_RENDER.getTargetFrameBufferViewportWidth() / (float) MC_RENDER.getTargetFrameBufferViewportHeight(), + RenderUtil.getNearClipPlaneDistanceInBlocks(partialTicks), + (float) ((lodDrawDistance + LodUtil.REGION_WIDTH) * Math.sqrt(2))); + + + // if (worldYOffsetUniform != -1) this.shader.setUniform(worldYOffsetUniform, (float) MC.getWrappedClientWorld().getMinHeight()); + + this.shader.setUniform(this.shader.getUniformLocation("gProj"), perspective); + GL32.glUniform1i(gDepthMapUniform, 0); // Fog this.shader.setUniform(fullFogModeUniform, MC_RENDER.isFogStateSpecial() ? 1 : 0); this.shader.setUniform(fogColorUniform, MC_RENDER.isFogStateSpecial() ? getSpecialFogColor(partialTicks) : getFogColor(partialTicks)); diff --git a/core/src/main/resources/shaders/fog/fog.frag b/core/src/main/resources/shaders/fog/fog.frag index e22281964..a487102dd 100644 --- a/core/src/main/resources/shaders/fog/fog.frag +++ b/core/src/main/resources/shaders/fog/fog.frag @@ -1,11 +1,14 @@ -in vec3 vertexWorldPos; +in vec2 TexCoord; + in float vertexYPos; //in uvec4 vPosition; //in vec2 TexCoord; out vec4 fragColor; +uniform sampler2D gDepthMap; +uniform mat4 gProj; uniform float fogScale; uniform float fogVerticalScale; @@ -43,6 +46,20 @@ float mod(float x, int y) { } +vec3 calcViewPosition(vec2 coords) { + float fragmentDepth = texture(gDepthMap, coords).r; + + vec4 ndc = vec4( + coords.x * 2.0 - 1.0, + coords.y * 2.0 - 1.0, + fragmentDepth * 2.0 - 1.0, + 1.0 + ); + + vec4 vs_pos = inverse(gProj) * ndc; + vs_pos.xyz = vs_pos.xyz / vs_pos.w; + return vs_pos.xyz; +} /** * Fragment shader for fog. @@ -51,6 +68,8 @@ float mod(float x, int y) { * version: 2023-6-21 */ void main() { + vec3 vertexWorldPos = calcViewPosition(TexCoord); + if (fullFogMode != 0) { fragColor = vec4(fogColor.r, fogColor.g, fogColor.b, 1.); } else { @@ -71,12 +90,12 @@ void main() { // Testing if (fragColor.r != 6969.) { // This line is so that the compiler doesnt delete the previos code - fragColor = vec4( - mod(vertexWorldPos.x, 1), - mod(vertexWorldPos.y, 1), - mod(vertexWorldPos.z, 1), - 1. - ); +// fragColor = vec4( +// mod(vertexWorldPos.x, 1), +// mod(vertexWorldPos.y, 1), +// mod(vertexWorldPos.z, 1), +// 1. +// ); // fragColor = vec4( // mod(vPosition.x, 1), // mod(vPosition.y, 1), diff --git a/core/src/main/resources/shaders/fog/fog.vert b/core/src/main/resources/shaders/fog/fog.vert deleted file mode 100644 index 0663c7a11..000000000 --- a/core/src/main/resources/shaders/fog/fog.vert +++ /dev/null @@ -1,22 +0,0 @@ -#version 150 core - - -//uniform vec3 modelOffset; -//uniform float worldYOffset; - -//in uvec4 vPosition; -in vec2 vPos; -out vec3 vertexWorldPos; -out float vertexYPos; - - -void main() -{ -// vertexWorldPos = vPosition.xyz + modelOffset; -// vertexWorldPos = vPosition.xyz; - vertexWorldPos = vec3(0.); - vertexYPos = 0.; -// vertexYPos = vPosition.y + worldYOffset; - - gl_Position = vec4(vPos, 1.0, 1.0); -} \ No newline at end of file From 76bc81233a9b973326e7209b6d24d7816ecbe296 Mon Sep 17 00:00:00 2001 From: coolGi Date: Wed, 2 Aug 2023 23:29:30 +0930 Subject: [PATCH 05/24] Removed old fog --- .../render/renderer/LodRenderProgram.java | 36 ++------- .../main/resources/shaders/flat_shaded.frag | 77 +------------------ core/src/main/resources/shaders/fog/fog.frag | 14 ++++ 3 files changed, 20 insertions(+), 107 deletions(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java index af7594cbc..83bbf669a 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java @@ -53,13 +53,6 @@ public class LodRenderProgram extends ShaderProgram public final int earthRadiusUniform; public final int lightMapUniform; - // Fog Uniforms - public final int fogColorUniform; - public final int fogScaleUniform; - public final int fogVerticalScaleUniform; - public final int nearFogStartUniform; - public final int nearFogLengthUniform;; - public final int fullFogModeUniform; // Noise Uniforms public final int noiseEnabledUniform; @@ -71,10 +64,11 @@ public class LodRenderProgram extends ShaderProgram // This will bind VertexAttribute public LodRenderProgram(LodFogConfig fogConfig) { - super(() -> Shader.loadFile(fogConfig.earthCurveRatio!=0 ? VERTEX_CURVE_SHADER_PATH : VERTEX_SHADER_PATH, - false, new StringBuilder()).toString(), - () -> fogConfig.loadAndProcessFragShader(FRAGMENT_SHADER_PATH, false).toString(), - "fragColor", new String[] { "vPosition", "color" }); + super( + fogConfig.earthCurveRatio!=0 ? VERTEX_CURVE_SHADER_PATH : VERTEX_SHADER_PATH, + FRAGMENT_SHADER_PATH, + "fragColor", new String[] { "vPosition", "color" } + ); this.fogConfig = fogConfig; combinedMatUniform = getUniformLocation("combinedMatrix"); @@ -85,15 +79,6 @@ public class LodRenderProgram extends ShaderProgram lightMapUniform = getUniformLocation("lightMap"); - // Fog Uniforms - fullFogModeUniform = getUniformLocation("fullFogMode"); - fogColorUniform = getUniformLocation("fogColor"); - fogScaleUniform = tryGetUniformLocation("fogScale"); - fogVerticalScaleUniform = tryGetUniformLocation("fogVerticalScale"); - // near - nearFogStartUniform = tryGetUniformLocation("nearFogStart"); - nearFogLengthUniform = tryGetUniformLocation("nearFogLength"); - // Noise Uniforms noiseEnabledUniform = getUniformLocation("noiseEnabled"); noiseStepsUniform = getUniformLocation("noiseSteps"); @@ -175,17 +160,6 @@ public class LodRenderProgram extends ShaderProgram setUniform(lightMapUniform, lightmapBindPoint); if (worldYOffsetUniform != -1) setUniform(worldYOffsetUniform, (float)worldYOffset); - - // Fog - setUniform(fullFogModeUniform, fullFogMode ? 1 : 0); - setUniform(fogColorUniform, fogColor); - - float nearFogLen = vanillaDrawDistance * 0.2f / lodDrawDistance; - float nearFogStart = vanillaDrawDistance * (VERSION_CONSTANTS.isVanillaRenderedChunkSquare() ? (float)Math.sqrt(2.) : 1.f) / lodDrawDistance; - if (nearFogStartUniform != -1) setUniform(nearFogStartUniform, nearFogStart); - if (nearFogLengthUniform != -1) setUniform(nearFogLengthUniform, nearFogLen); - if (fogScaleUniform != -1) setUniform(fogScaleUniform, 1.f/lodDrawDistance); - if (fogVerticalScaleUniform != -1) setUniform(fogVerticalScaleUniform, 1.f/worldHeight); } public void setModelPos(Vec3f modelPos) { diff --git a/core/src/main/resources/shaders/flat_shaded.frag b/core/src/main/resources/shaders/flat_shaded.frag index 014abece5..a8a092321 100644 --- a/core/src/main/resources/shaders/flat_shaded.frag +++ b/core/src/main/resources/shaders/flat_shaded.frag @@ -1,3 +1,4 @@ +#version 150 core in vec4 vertexColor; in vec3 vertexWorldPos; @@ -6,45 +7,12 @@ in vec4 vPos; out vec4 fragColor; -// Fog Uniforms -uniform float fogScale; -uniform float fogVerticalScale; -uniform float nearFogStart; -uniform float nearFogLength; -uniform int fullFogMode; - // Noise Uniforms uniform bool noiseEnabled; uniform int noiseSteps; uniform float noiseIntensity; uniform int noiseDropoff; -/* ========MARCO DEFINED BY RUNTIME CODE GEN========= - -float farFogStart; -float farFogLength; -float farFogMin; -float farFogRange; -float farFogDensity; - -float heightFogStart; -float heightFogLength; -float heightFogMin; -float heightFogRange; -float heightFogDensity; -*/ - -uniform vec4 fogColor; - -// method definitions -// ==== The below 5 methods will be run-time generated. ==== -float getNearFogThickness(float dist); -float getFarFogThickness(float dist); -float getHeightFogThickness(float dist); -float calculateFarFogDepth(float horizontal, float dist, float nearFogStart); -float calculateHeightFogDepth(float vertical, float realY); -float mixFogThickness(float near, float far, float height); -// ========================================================= float fade(float value, float start, float end) { return (clamp(value,start,end)-start)/(end-start); @@ -155,47 +123,4 @@ void main() // fragColor.w); // } } - - // TODO: Move into its own function instead of in an if statement - if (fullFogMode != 0) { - fragColor = vec4(fogColor.rgb, 1.0); - } else { - // TODO: add a white texture to support Optifine shaders - //vec4 textureColor = texture(texImage, textureCoord); - //fragColor = vertexColor * textureColor; - - float horizontalDist = length(vertexWorldPos.xz) * fogScale; - float heightDist = calculateHeightFogDepth( - vertexWorldPos.y, vertexYPos) * fogVerticalScale; - float farDist = calculateFarFogDepth(horizontalDist, - length(vertexWorldPos.xyz) * fogScale, nearFogStart); - - float nearFogThickness = getNearFogThickness(horizontalDist); - float farFogThickness = getFarFogThickness(farDist); - float heightFogThickness = getHeightFogThickness(heightDist); - float mixedFogThickness = clamp(mixFogThickness( - nearFogThickness, farFogThickness, heightFogThickness), 0.0, 1.0); - - fragColor = mix(fragColor, vec4(fogColor.rgb, 1.0), mixedFogThickness); - } -} - - - -// Are these still needed? -float linearFog(float x, float fogStart, float fogLength, float fogMin, float fogRange) { - x = clamp((x-fogStart)/fogLength, 0.0, 1.0); - return fogMin + fogRange * x; -} - -float exponentialFog(float x, float fogStart, float fogLength, - float fogMin, float fogRange, float fogDensity) { - x = max((x-fogStart)/fogLength, 0.0) * fogDensity; - return fogMin + fogRange - fogRange/exp(x); -} - -float exponentialSquaredFog(float x, float fogStart, float fogLength, - float fogMin, float fogRange, float fogDensity) { - x = max((x-fogStart)/fogLength, 0.0) * fogDensity; - return fogMin + fogRange - fogRange/exp(x*x); } \ No newline at end of file diff --git a/core/src/main/resources/shaders/fog/fog.frag b/core/src/main/resources/shaders/fog/fog.frag index a487102dd..ab81122ee 100644 --- a/core/src/main/resources/shaders/fog/fog.frag +++ b/core/src/main/resources/shaders/fog/fog.frag @@ -19,6 +19,20 @@ uniform int fullFogMode; uniform vec4 fogColor; +/* ========MARCO DEFINED BY RUNTIME CODE GEN========= + +float farFogStart; +float farFogLength; +float farFogMin; +float farFogRange; +float farFogDensity; + +float heightFogStart; +float heightFogLength; +float heightFogMin; +float heightFogRange; +float heightFogDensity; +*/ // method definitions // ==== The below 5 methods will be run-time generated. ==== From 146c2e6f1ca560159a6d9a92c2c1c068cb3f7940 Mon Sep 17 00:00:00 2001 From: coolGi Date: Sat, 5 Aug 2023 14:58:03 +0930 Subject: [PATCH 06/24] Final save commit for another attempt to fix fog, before revert. --- core/src/main/resources/shaders/fog/fog.frag | 21 +++++++------------- core/src/main/resources/shaders/ssao/ao.frag | 1 - 2 files changed, 7 insertions(+), 15 deletions(-) diff --git a/core/src/main/resources/shaders/fog/fog.frag b/core/src/main/resources/shaders/fog/fog.frag index ab81122ee..d19f59906 100644 --- a/core/src/main/resources/shaders/fog/fog.frag +++ b/core/src/main/resources/shaders/fog/fog.frag @@ -1,9 +1,7 @@ in vec2 TexCoord; -in float vertexYPos; -//in uvec4 vPosition; -//in vec2 TexCoord; +//in float vertexYPos; out vec4 fragColor; @@ -82,6 +80,7 @@ vec3 calcViewPosition(vec2 coords) { * version: 2023-6-21 */ void main() { + float vertexYPos = 100f; vec3 vertexWorldPos = calcViewPosition(TexCoord); if (fullFogMode != 0) { @@ -103,20 +102,14 @@ void main() { } // Testing - if (fragColor.r != 6969.) { // This line is so that the compiler doesnt delete the previos code +// if (fragColor.r != 6969.) { // This line is so that the compiler doesnt delete the previos code // fragColor = vec4( -// mod(vertexWorldPos.x, 1), -// mod(vertexWorldPos.y, 1), -// mod(vertexWorldPos.z, 1), +// mod(texture(gDepthMap, TexCoord).x, 1), +// mod(texture(gDepthMap, TexCoord).y, 1), +// mod(texture(gDepthMap, TexCoord).z, 1), // 1. // ); -// fragColor = vec4( -// mod(vPosition.x, 1), -// mod(vPosition.y, 1), -// mod(vPosition.z, 1), -// 1. -// ); - } +// } } diff --git a/core/src/main/resources/shaders/ssao/ao.frag b/core/src/main/resources/shaders/ssao/ao.frag index d8d77ccf0..15f648764 100644 --- a/core/src/main/resources/shaders/ssao/ao.frag +++ b/core/src/main/resources/shaders/ssao/ao.frag @@ -1,7 +1,6 @@ #version 150 core in vec2 TexCoord; -in vec2 ViewRay; out vec4 fragColor; From 5800029206a2727414b7c4f6a93633178548ce0d Mon Sep 17 00:00:00 2001 From: coolGi Date: Sat, 5 Aug 2023 15:03:26 +0930 Subject: [PATCH 07/24] Reverted previous removing fog from main shader --- .../render/renderer/LodRenderProgram.java | 37 +++++- .../core/render/renderer/LodRenderer.java | 2 +- .../main/resources/shaders/flat_shaded.frag | 122 ++++++++++++++---- 3 files changed, 132 insertions(+), 29 deletions(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java index 83bbf669a..cecf49059 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java @@ -54,6 +54,14 @@ public class LodRenderProgram extends ShaderProgram public final int lightMapUniform; + // Fog Uniforms + public final int fogColorUniform; + public final int fogScaleUniform; + public final int fogVerticalScaleUniform; + public final int nearFogStartUniform; + public final int nearFogLengthUniform;; + public final int fullFogModeUniform; + // Noise Uniforms public final int noiseEnabledUniform; public final int noiseStepsUniform; @@ -64,11 +72,10 @@ public class LodRenderProgram extends ShaderProgram // This will bind VertexAttribute public LodRenderProgram(LodFogConfig fogConfig) { - super( - fogConfig.earthCurveRatio!=0 ? VERTEX_CURVE_SHADER_PATH : VERTEX_SHADER_PATH, - FRAGMENT_SHADER_PATH, - "fragColor", new String[] { "vPosition", "color" } - ); + super(() -> Shader.loadFile(fogConfig.earthCurveRatio!=0 ? VERTEX_CURVE_SHADER_PATH : VERTEX_SHADER_PATH, + false, new StringBuilder()).toString(), + () -> fogConfig.loadAndProcessFragShader(FRAGMENT_SHADER_PATH, false).toString(), + "fragColor", new String[] { "vPosition", "color" }); this.fogConfig = fogConfig; combinedMatUniform = getUniformLocation("combinedMatrix"); @@ -79,6 +86,15 @@ public class LodRenderProgram extends ShaderProgram lightMapUniform = getUniformLocation("lightMap"); + // Fog Uniforms + fullFogModeUniform = getUniformLocation("fullFogMode"); + fogColorUniform = getUniformLocation("fogColor"); + fogScaleUniform = tryGetUniformLocation("fogScale"); + fogVerticalScaleUniform = tryGetUniformLocation("fogVerticalScale"); + // near + nearFogStartUniform = tryGetUniformLocation("nearFogStart"); + nearFogLengthUniform = tryGetUniformLocation("nearFogLength"); + // Noise Uniforms noiseEnabledUniform = getUniformLocation("noiseEnabled"); noiseStepsUniform = getUniformLocation("noiseSteps"); @@ -160,6 +176,17 @@ public class LodRenderProgram extends ShaderProgram setUniform(lightMapUniform, lightmapBindPoint); if (worldYOffsetUniform != -1) setUniform(worldYOffsetUniform, (float)worldYOffset); + + // Fog + setUniform(fullFogModeUniform, fullFogMode ? 1 : 0); + setUniform(fogColorUniform, fogColor); + + float nearFogLen = vanillaDrawDistance * 0.2f / lodDrawDistance; + float nearFogStart = vanillaDrawDistance * (VERSION_CONSTANTS.isVanillaRenderedChunkSquare() ? (float)Math.sqrt(2.) : 1.f) / lodDrawDistance; + if (nearFogStartUniform != -1) setUniform(nearFogStartUniform, nearFogStart); + if (nearFogLengthUniform != -1) setUniform(nearFogLengthUniform, nearFogLen); + if (fogScaleUniform != -1) setUniform(fogScaleUniform, 1.f/lodDrawDistance); + if (fogVerticalScaleUniform != -1) setUniform(fogVerticalScaleUniform, 1.f/worldHeight); } public void setModelPos(Vec3f modelPos) { diff --git a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderer.java b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderer.java index 6f5c571a0..f622276af 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderer.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderer.java @@ -256,7 +256,7 @@ public class LodRenderer SSAORenderer.INSTANCE.render(partialTicks); } { - FogShader.INSTANCE.render(partialTicks); +// FogShader.INSTANCE.render(partialTicks); // DarkShader.INSTANCE.render(partialTicks); // A test shader to make the world darker } diff --git a/core/src/main/resources/shaders/flat_shaded.frag b/core/src/main/resources/shaders/flat_shaded.frag index a8a092321..0252c0b4c 100644 --- a/core/src/main/resources/shaders/flat_shaded.frag +++ b/core/src/main/resources/shaders/flat_shaded.frag @@ -1,4 +1,3 @@ -#version 150 core in vec4 vertexColor; in vec3 vertexWorldPos; @@ -7,12 +6,45 @@ in vec4 vPos; out vec4 fragColor; +// Fog Uniforms +uniform float fogScale; +uniform float fogVerticalScale; +uniform float nearFogStart; +uniform float nearFogLength; +uniform int fullFogMode; + // Noise Uniforms uniform bool noiseEnabled; uniform int noiseSteps; uniform float noiseIntensity; uniform int noiseDropoff; +/* ========MARCO DEFINED BY RUNTIME CODE GEN========= + +float farFogStart; +float farFogLength; +float farFogMin; +float farFogRange; +float farFogDensity; + +float heightFogStart; +float heightFogLength; +float heightFogMin; +float heightFogRange; +float heightFogDensity; +*/ + +uniform vec4 fogColor; + +// method definitions +// ==== The below 5 methods will be run-time generated. ==== +float getNearFogThickness(float dist); +float getFarFogThickness(float dist); +float getHeightFogThickness(float dist); +float calculateFarFogDepth(float horizontal, float dist, float nearFogStart); +float calculateHeightFogDepth(float vertical, float realY); +float mixFogThickness(float near, float far, float height); +// ========================================================= float fade(float value, float start, float end) { return (clamp(value,start,end)-start)/(end-start); @@ -64,7 +96,7 @@ vec3 HSV2RGB(vec3 c) { */ void main() { - fragColor = vertexColor; + fragColor = vertexColor; // TODO: Move into its own function instead of in an if statement @@ -72,9 +104,9 @@ void main() vec3 vertexNormal = normalize(cross(dFdx(vPos.xyz), dFdy(vPos.xyz))); // This bit of code is required to fix the vertex position problem cus of floats in the verted world position varuable vec3 fixedVPos = vec3( - vPos.x - vertexNormal.x * 0.001, - vPos.y - vertexNormal.y * 0.001, - vPos.z - vertexNormal.z * 0.001 + vPos.x - vertexNormal.x * 0.001, + vPos.y - vertexNormal.y * 0.001, + vPos.z - vertexNormal.z * 0.001 ); @@ -84,9 +116,9 @@ void main() // Random value for each position float randomValue = rand(vec3( - quantize(fixedVPos.x, noiseSteps), - quantize(fixedVPos.y, noiseSteps), - quantize(fixedVPos.z, noiseSteps) + quantize(fixedVPos.x, noiseSteps), + quantize(fixedVPos.y, noiseSteps), + quantize(fixedVPos.z, noiseSteps) )) * 2. * noiseAmplification - noiseAmplification; @@ -97,22 +129,22 @@ void main() // Clamps it and turns it back into a vec4 if (noiseDropoff == 0) - fragColor = vec4( - clamp(newCol.r, 0., 1.), - clamp(newCol.g, 0., 1.), - clamp(newCol.b, 0., 1.), - fragColor.w - ); + fragColor = vec4( + clamp(newCol.r, 0., 1.), + clamp(newCol.g, 0., 1.), + clamp(newCol.b, 0., 1.), + fragColor.w + ); else - fragColor = mix( - vec4( - clamp(newCol.r, 0., 1.), - clamp(newCol.g, 0., 1.), - clamp(newCol.b, 0., 1.), - fragColor.w - ), fragColor, - clamp(length(vertexWorldPos) / noiseDropoff, 0., 1.) // The further away it gets, the less noise gets applied - ); + fragColor = mix( + vec4( + clamp(newCol.r, 0., 1.), + clamp(newCol.g, 0., 1.), + clamp(newCol.b, 0., 1.), + fragColor.w + ), fragColor, + clamp(length(vertexWorldPos) / noiseDropoff, 0., 1.) // The further away it gets, the less noise gets applied + ); // For testing // if (fragColor.r != 69420.) { @@ -123,4 +155,48 @@ void main() // fragColor.w); // } } + + // TODO: Move into its own function instead of in an if statement + // This is so that it can apply after the SSAO (work for this has started in the FogShader file and fog/fog.frag shader) + if (fullFogMode != 0) { + fragColor = vec4(fogColor.rgb, 1.0); + } else { + // TODO: add a white texture to support Optifine shaders + //vec4 textureColor = texture(texImage, textureCoord); + //fragColor = vertexColor * textureColor; + + float horizontalDist = length(vertexWorldPos.xz) * fogScale; + float heightDist = calculateHeightFogDepth( + vertexWorldPos.y, vertexYPos) * fogVerticalScale; + float farDist = calculateFarFogDepth(horizontalDist, + length(vertexWorldPos.xyz) * fogScale, nearFogStart); + + float nearFogThickness = getNearFogThickness(horizontalDist); + float farFogThickness = getFarFogThickness(farDist); + float heightFogThickness = getHeightFogThickness(heightDist); + float mixedFogThickness = clamp(mixFogThickness( + nearFogThickness, farFogThickness, heightFogThickness), 0.0, 1.0); + + fragColor = mix(fragColor, vec4(fogColor.rgb, 1.0), mixedFogThickness); + } +} + + + +// Are these still needed? +float linearFog(float x, float fogStart, float fogLength, float fogMin, float fogRange) { + x = clamp((x-fogStart)/fogLength, 0.0, 1.0); + return fogMin + fogRange * x; +} + +float exponentialFog(float x, float fogStart, float fogLength, +float fogMin, float fogRange, float fogDensity) { + x = max((x-fogStart)/fogLength, 0.0) * fogDensity; + return fogMin + fogRange - fogRange/exp(x); +} + +float exponentialSquaredFog(float x, float fogStart, float fogLength, +float fogMin, float fogRange, float fogDensity) { + x = max((x-fogStart)/fogLength, 0.0) * fogDensity; + return fogMin + fogRange - fogRange/exp(x*x); } \ No newline at end of file From 783ceeb6332d7f522c2c90617616457305cd2488 Mon Sep 17 00:00:00 2001 From: coolGi Date: Sat, 5 Aug 2023 16:53:41 +0930 Subject: [PATCH 08/24] Some general fixes --- Readme.md | 2 +- .../core/jar/gui/BaseJFrame.java | 9 ++-- .../assets/distanthorizons/lang/en_us.json | 2 +- .../main/resources/shaders/flat_shaded.frag | 48 +++++++++---------- 4 files changed, 30 insertions(+), 31 deletions(-) diff --git a/Readme.md b/Readme.md index ba593171f..668aca089 100644 --- a/Readme.md +++ b/Readme.md @@ -17,7 +17,7 @@ It should be automatically included when pulling the full mod. LZ4 for Java (data compression)\ https://github.com/lz4/lz4-java -Json & Toml for Java (config handling)\ +NightConfig for Json & Toml (config handling)\ https://github.com/TheElectronWill/night-config SVG Salamander for SVG's\ diff --git a/core/src/main/java/com/seibel/distanthorizons/core/jar/gui/BaseJFrame.java b/core/src/main/java/com/seibel/distanthorizons/core/jar/gui/BaseJFrame.java index 546e860ab..344d792dd 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/jar/gui/BaseJFrame.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/jar/gui/BaseJFrame.java @@ -59,7 +59,7 @@ public class BaseJFrame extends JFrame { // Creates a list with all the options in it List langsToChoose = new ArrayList<>(); try( - final InputStreamReader isr = new InputStreamReader(JarUtils.accessFile("assets/lod/lang"), StandardCharsets.UTF_8); + final InputStreamReader isr = new InputStreamReader(JarUtils.accessFile("assets/distanthorizons/lang"), StandardCharsets.UTF_8); final BufferedReader br = new BufferedReader(isr) ) { List col = Collections.unmodifiableList(new ArrayList<>(Arrays.asList(br.lines().toArray()))); @@ -87,11 +87,11 @@ public class BaseJFrame extends JFrame { // Try to set the icons for them try { lightMode = new JButton(new ImageIcon( - new FlatSVGIcon(JarUtils.accessFile("assets/lod/textures/jar/themeLight.svg")).getImage() // Get the image + new FlatSVGIcon(JarUtils.accessFile("assets/distanthorizons/textures/jar/themeLight.svg")).getImage() // Get the image .getScaledInstance(themeButtonSize, themeButtonSize, Image.SCALE_DEFAULT) // Scale it to the correct size )); darkMode = new JButton(new ImageIcon( - new FlatSVGIcon(JarUtils.accessFile("assets/lod/textures/jar/themeDark.svg")).getImage() // Get the image + new FlatSVGIcon(JarUtils.accessFile("assets/distanthorizons/textures/jar/themeDark.svg")).getImage() // Get the image .getScaledInstance(themeButtonSize, themeButtonSize, Image.SCALE_DEFAULT) // Scale it to the correct size )); } catch (Exception e) {e.printStackTrace();} @@ -139,8 +139,7 @@ public class BaseJFrame extends JFrame { // This part of the code is taken from the official java docs at https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html // Specify the look and feel to use by defining the LOOKANDFEEL constant - // Valid values are: null (use the default), "Metal", "System", "Motif", - // and "GTK" + // Valid values are: null (use the default), "Metal", "System", "Motif", and "GTK" final static String LOOKANDFEEL = "GTK"; private static void initLookAndFeel() { String lookAndFeel = null; diff --git a/core/src/main/resources/assets/distanthorizons/lang/en_us.json b/core/src/main/resources/assets/distanthorizons/lang/en_us.json index c4da69c7b..1bdabf28d 100644 --- a/core/src/main/resources/assets/distanthorizons/lang/en_us.json +++ b/core/src/main/resources/assets/distanthorizons/lang/en_us.json @@ -224,7 +224,7 @@ "distanthorizons.config.client.advanced.graphics.noiseTextureSettings.noiseDropoff": "Noise Dropoff", "distanthorizons.config.client.advanced.graphics.noiseTextureSettings.noiseDropoff.@tooltip": - "How far should the noise texture render before it fades away? \n\n0.0 - the noise texture will render the entire LOD render distance. \n3.0 - the noise texture will fade away at 1/3 of the LOD render distance. ", + "Defines how far should the noise texture render before it fades away. (in blocks). \nSet to 0 to disable noise from fading away.", "distanthorizons.config.client.advanced.graphics.advancedGraphics": diff --git a/core/src/main/resources/shaders/flat_shaded.frag b/core/src/main/resources/shaders/flat_shaded.frag index 0252c0b4c..99a6b47ec 100644 --- a/core/src/main/resources/shaders/flat_shaded.frag +++ b/core/src/main/resources/shaders/flat_shaded.frag @@ -104,9 +104,9 @@ void main() vec3 vertexNormal = normalize(cross(dFdx(vPos.xyz), dFdy(vPos.xyz))); // This bit of code is required to fix the vertex position problem cus of floats in the verted world position varuable vec3 fixedVPos = vec3( - vPos.x - vertexNormal.x * 0.001, - vPos.y - vertexNormal.y * 0.001, - vPos.z - vertexNormal.z * 0.001 + vPos.x - vertexNormal.x * 0.001, + vPos.y - vertexNormal.y * 0.001, + vPos.z - vertexNormal.z * 0.001 ); @@ -116,9 +116,9 @@ void main() // Random value for each position float randomValue = rand(vec3( - quantize(fixedVPos.x, noiseSteps), - quantize(fixedVPos.y, noiseSteps), - quantize(fixedVPos.z, noiseSteps) + quantize(fixedVPos.x, noiseSteps), + quantize(fixedVPos.y, noiseSteps), + quantize(fixedVPos.z, noiseSteps) )) * 2. * noiseAmplification - noiseAmplification; @@ -129,22 +129,22 @@ void main() // Clamps it and turns it back into a vec4 if (noiseDropoff == 0) - fragColor = vec4( - clamp(newCol.r, 0., 1.), - clamp(newCol.g, 0., 1.), - clamp(newCol.b, 0., 1.), - fragColor.w - ); + fragColor = vec4( + clamp(newCol.r, 0., 1.), + clamp(newCol.g, 0., 1.), + clamp(newCol.b, 0., 1.), + fragColor.w + ); else - fragColor = mix( - vec4( - clamp(newCol.r, 0., 1.), - clamp(newCol.g, 0., 1.), - clamp(newCol.b, 0., 1.), - fragColor.w - ), fragColor, - clamp(length(vertexWorldPos) / noiseDropoff, 0., 1.) // The further away it gets, the less noise gets applied - ); + fragColor = mix( + vec4( + clamp(newCol.r, 0., 1.), + clamp(newCol.g, 0., 1.), + clamp(newCol.b, 0., 1.), + fragColor.w + ), fragColor, + clamp(length(vertexWorldPos) / noiseDropoff, 0., 1.) // The further away it gets, the less noise gets applied + ); // For testing // if (fragColor.r != 69420.) { @@ -167,15 +167,15 @@ void main() float horizontalDist = length(vertexWorldPos.xz) * fogScale; float heightDist = calculateHeightFogDepth( - vertexWorldPos.y, vertexYPos) * fogVerticalScale; + vertexWorldPos.y, vertexYPos) * fogVerticalScale; float farDist = calculateFarFogDepth(horizontalDist, - length(vertexWorldPos.xyz) * fogScale, nearFogStart); + length(vertexWorldPos.xyz) * fogScale, nearFogStart); float nearFogThickness = getNearFogThickness(horizontalDist); float farFogThickness = getFarFogThickness(farDist); float heightFogThickness = getHeightFogThickness(heightDist); float mixedFogThickness = clamp(mixFogThickness( - nearFogThickness, farFogThickness, heightFogThickness), 0.0, 1.0); + nearFogThickness, farFogThickness, heightFogThickness), 0.0, 1.0); fragColor = mix(fragColor, vec4(fogColor.rgb, 1.0), mixedFogThickness); } From ff1a1d51641ea6c04fb8b1955c1bc30c8a765900 Mon Sep 17 00:00:00 2001 From: James Seibel Date: Sat, 5 Aug 2023 22:21:58 -0500 Subject: [PATCH 09/24] minor FullDataToRenderDataTransformer refactor --- .../transformers/FullDataToRenderDataTransformer.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/transformers/FullDataToRenderDataTransformer.java b/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/transformers/FullDataToRenderDataTransformer.java index a9b0663a5..6fd140464 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/transformers/FullDataToRenderDataTransformer.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/transformers/FullDataToRenderDataTransformer.java @@ -29,7 +29,8 @@ import com.seibel.distanthorizons.coreapi.util.BitShiftUtil; */ public class FullDataToRenderDataTransformer { - private static final IBlockStateWrapper AIR = SingletonInjector.INSTANCE.get(IWrapperFactory.class).getAirBlockStateWrapper(); + private static final IWrapperFactory WRAPPER_FACTORY = SingletonInjector.INSTANCE.get(IWrapperFactory.class); + private static final IBlockStateWrapper AIR = WRAPPER_FACTORY.getAirBlockStateWrapper(); From 13459827956d5b07f7301c83ff20f0f89ecc9f36 Mon Sep 17 00:00:00 2001 From: James Seibel Date: Sat, 5 Aug 2023 22:22:51 -0500 Subject: [PATCH 10/24] Comment out all Netty related files Done to allow 1.16 to compile --- .../core/api/internal/ClientApi.java | 236 +++++++-------- .../core/network/NetworkClient.java | 282 +++++++++--------- .../core/network/NetworkEventSource.java | 78 ++--- .../core/network/NetworkServer.java | 182 +++++------ .../core/network/messages/AckMessage.java | 12 +- .../core/network/messages/CloseMessage.java | 12 +- .../network/messages/CloseReasonMessage.java | 12 +- .../core/network/messages/HelloMessage.java | 12 +- .../network/messages/PlayerUUIDMessage.java | 20 +- .../messages/RemotePlayerConfigMessage.java | 12 +- .../messages/RequestChunksMessage.java | 24 +- .../core/network/objects/RemotePlayer.java | 16 +- .../core/network/protocol/INetworkObject.java | 44 +-- .../core/network/protocol/MessageDecoder.java | 20 +- .../core/network/protocol/MessageEncoder.java | 20 +- .../core/network/protocol/MessageHandler.java | 74 ++--- .../protocol/NetworkChannelInitializer.java | 48 +-- .../protocol/NetworkExceptionHandler.java | 18 +- .../NetworkOutboundExceptionRouter.java | 22 +- .../core/world/DhClientWorld.java | 54 ++-- .../core/world/DhServerWorld.java | 118 ++++---- 21 files changed, 658 insertions(+), 658 deletions(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/api/internal/ClientApi.java b/core/src/main/java/com/seibel/distanthorizons/core/api/internal/ClientApi.java index 84122c405..750ca3997 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/api/internal/ClientApi.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/api/internal/ClientApi.java @@ -46,7 +46,7 @@ import com.seibel.distanthorizons.core.wrapperInterfaces.minecraft.IMinecraftCli import com.seibel.distanthorizons.core.wrapperInterfaces.minecraft.IMinecraftRenderWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.minecraft.IProfilerWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IClientLevelWrapper; -import io.netty.buffer.ByteBuf; +//import io.netty.buffer.ByteBuf; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.lwjgl.glfw.GLFW; @@ -329,123 +329,123 @@ public class ClientApi // networking // //============// - /** @param byteBuf is Netty's {@link ByteBuffer} wrapper. */ - public void serverMessageReceived(ByteBuf byteBuf) - { - if (!Config.Client.Advanced.Multiplayer.enableMultiverseNetworking.get()) - { - // multiverse networking disabled, ignore anything sent from the server - return; - } - - - - // either value can be set to true to debug the received byte stream - boolean stopAndDisplayInputAsByteArray = false; - boolean stopAndDisplayInputAsString = false; - if (stopAndDisplayInputAsByteArray || stopAndDisplayInputAsString) - { - String messageString = ""; - if (stopAndDisplayInputAsByteArray) - { - int byteCount = byteBuf.readableBytes(); - byte[] arr = new byte[byteCount]; - StringBuilder stringBuilder = new StringBuilder("Server message received: ["); - for (int i = 0; i < byteCount; i++) - { - arr[i] = byteBuf.readByte(); - stringBuilder.append(arr[i]); - } - stringBuilder.append("]"); - - messageString = stringBuilder.toString(); - } - else if (stopAndDisplayInputAsString) - { - messageString = byteBuf.toString(StandardCharsets.UTF_8); - } - - // this is logged as an error so it is easier to see in an Intellij log - LOGGER.error(messageString); - return; - } - - - - - // It is important to ensure malicious server input is ignored. - if (this.serverNetworkingIsMalformed) - { - return; - } - - // check that the incoming message is within the expected size - short commandLength = byteBuf.readShort(); - if (commandLength < 1 || commandLength > 32) - { - LOGGER.error("Server command length ["+commandLength+"] outside the expected range of 1 to 32 (inclusive)."); - ClientApi.INSTANCE.serverNetworkingIsMalformed = true; - return; - } - - // parse the command - String eventType; - try - { - eventType = byteBuf.readCharSequence(commandLength, StandardCharsets.UTF_8).toString(); - } - catch (Exception e) - { - LOGGER.error("Server sent un-parsable command. Error: "+e.getMessage()); - return; - } - - switch (eventType) - { - case "ServerCommsEnabled": - LOGGER.info("Server supports DH multiverse protocol."); - ClientApi.INSTANCE.isServerCommunicationEnabled = true; - KEYED_CLIENT_LEVEL_MANAGER.setUseOverrideWrapper(true); - MC.executeOnRenderThread(() -> - { - // Unload the current world, since it may be wrong. - // A followup WorldChanged event should be received from the server soon after this. - LOGGER.info("Unloading current client level so the server can define the correct multiverse level."); - this.clientLevelUnloadEvent((IClientLevelWrapper) MC.getWrappedClientWorld()); - }); - break; - - case "LevelChanged": - short levelKeyLength = byteBuf.readShort(); - if (levelKeyLength < 1 || levelKeyLength > 128) // TODO 128 should be put into a constant somewhere - { - LOGGER.error("Server [LevelChanged] command length ["+commandLength+"] outside the expected range of 1 to 128 (inclusive)."); - this.serverNetworkingIsMalformed = true; - return; - } - - String levelKey = byteBuf.readCharSequence(levelKeyLength, StandardCharsets.UTF_8).toString(); - if (!levelKey.matches("[a-zA-Z0-9_]+")) - { - LOGGER.error("Server sent invalid world key name, and is being ignored."); - this.isServerCommunicationEnabled = false; - this.serverNetworkingIsMalformed = true; - return; - } - - LOGGER.info("Server level change event received, changing the level to ["+levelKey+"]."); - MC.executeOnRenderThread(() -> { - if (MC.getWrappedClientWorld() != null) - { - this.clientLevelUnloadEvent((IClientLevelWrapper) MC.getWrappedClientWorld()); - } - IServerKeyedClientLevel clientLevel = KEYED_CLIENT_LEVEL_MANAGER.getServerKeyedLevel(MC.getWrappedClientWorld(), levelKey); - KEYED_CLIENT_LEVEL_MANAGER.setServerKeyedLevel(clientLevel); - this.multiverseClientLevelLoadEvent(clientLevel); - }); - break; - } - } +// /** @param byteBuf is Netty's {@link ByteBuffer} wrapper. */ +// public void serverMessageReceived(ByteBuf byteBuf) +// { +// if (!Config.Client.Advanced.Multiplayer.enableMultiverseNetworking.get()) +// { +// // multiverse networking disabled, ignore anything sent from the server +// return; +// } +// +// +// +// // either value can be set to true to debug the received byte stream +// boolean stopAndDisplayInputAsByteArray = false; +// boolean stopAndDisplayInputAsString = false; +// if (stopAndDisplayInputAsByteArray || stopAndDisplayInputAsString) +// { +// String messageString = ""; +// if (stopAndDisplayInputAsByteArray) +// { +// int byteCount = byteBuf.readableBytes(); +// byte[] arr = new byte[byteCount]; +// StringBuilder stringBuilder = new StringBuilder("Server message received: ["); +// for (int i = 0; i < byteCount; i++) +// { +// arr[i] = byteBuf.readByte(); +// stringBuilder.append(arr[i]); +// } +// stringBuilder.append("]"); +// +// messageString = stringBuilder.toString(); +// } +// else if (stopAndDisplayInputAsString) +// { +// messageString = byteBuf.toString(StandardCharsets.UTF_8); +// } +// +// // this is logged as an error so it is easier to see in an Intellij log +// LOGGER.error(messageString); +// return; +// } +// +// +// +// +// // It is important to ensure malicious server input is ignored. +// if (this.serverNetworkingIsMalformed) +// { +// return; +// } +// +// // check that the incoming message is within the expected size +// short commandLength = byteBuf.readShort(); +// if (commandLength < 1 || commandLength > 32) +// { +// LOGGER.error("Server command length ["+commandLength+"] outside the expected range of 1 to 32 (inclusive)."); +// ClientApi.INSTANCE.serverNetworkingIsMalformed = true; +// return; +// } +// +// // parse the command +// String eventType; +// try +// { +// eventType = byteBuf.readCharSequence(commandLength, StandardCharsets.UTF_8).toString(); +// } +// catch (Exception e) +// { +// LOGGER.error("Server sent un-parsable command. Error: "+e.getMessage()); +// return; +// } +// +// switch (eventType) +// { +// case "ServerCommsEnabled": +// LOGGER.info("Server supports DH multiverse protocol."); +// ClientApi.INSTANCE.isServerCommunicationEnabled = true; +// KEYED_CLIENT_LEVEL_MANAGER.setUseOverrideWrapper(true); +// MC.executeOnRenderThread(() -> +// { +// // Unload the current world, since it may be wrong. +// // A followup WorldChanged event should be received from the server soon after this. +// LOGGER.info("Unloading current client level so the server can define the correct multiverse level."); +// this.clientLevelUnloadEvent((IClientLevelWrapper) MC.getWrappedClientWorld()); +// }); +// break; +// +// case "LevelChanged": +// short levelKeyLength = byteBuf.readShort(); +// if (levelKeyLength < 1 || levelKeyLength > 128) // TODO 128 should be put into a constant somewhere +// { +// LOGGER.error("Server [LevelChanged] command length ["+commandLength+"] outside the expected range of 1 to 128 (inclusive)."); +// this.serverNetworkingIsMalformed = true; +// return; +// } +// +// String levelKey = byteBuf.readCharSequence(levelKeyLength, StandardCharsets.UTF_8).toString(); +// if (!levelKey.matches("[a-zA-Z0-9_]+")) +// { +// LOGGER.error("Server sent invalid world key name, and is being ignored."); +// this.isServerCommunicationEnabled = false; +// this.serverNetworkingIsMalformed = true; +// return; +// } +// +// LOGGER.info("Server level change event received, changing the level to ["+levelKey+"]."); +// MC.executeOnRenderThread(() -> { +// if (MC.getWrappedClientWorld() != null) +// { +// this.clientLevelUnloadEvent((IClientLevelWrapper) MC.getWrappedClientWorld()); +// } +// IServerKeyedClientLevel clientLevel = KEYED_CLIENT_LEVEL_MANAGER.getServerKeyedLevel(MC.getWrappedClientWorld(), levelKey); +// KEYED_CLIENT_LEVEL_MANAGER.setServerKeyedLevel(clientLevel); +// this.multiverseClientLevelLoadEvent(clientLevel); +// }); +// break; +// } +// } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/NetworkClient.java b/core/src/main/java/com/seibel/distanthorizons/core/network/NetworkClient.java index e2b3a4d61..599fc771c 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/NetworkClient.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/NetworkClient.java @@ -5,152 +5,152 @@ import com.seibel.distanthorizons.core.network.messages.CloseMessage; import com.seibel.distanthorizons.core.network.messages.CloseReasonMessage; import com.seibel.distanthorizons.core.network.messages.HelloMessage; import com.seibel.distanthorizons.core.network.protocol.NetworkChannelInitializer; -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelOption; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioSocketChannel; +//import io.netty.bootstrap.Bootstrap; +//import io.netty.channel.Channel; +//import io.netty.channel.ChannelFuture; +//import io.netty.channel.ChannelOption; +//import io.netty.channel.EventLoopGroup; +//import io.netty.channel.nio.NioEventLoopGroup; +//import io.netty.channel.socket.nio.NioSocketChannel; import org.apache.logging.log4j.Logger; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; -public class NetworkClient extends NetworkEventSource implements AutoCloseable +public class NetworkClient //extends NetworkEventSource implements AutoCloseable { - private static final Logger LOGGER = DhLoggerBuilder.getLogger(); - - private enum EConnectionState - { - OPEN, - RECONNECT, - RECONNECT_FORCE, - CLOSE_WAIT, - CLOSED - } - - private static final int FAILURE_RECONNECT_DELAY_SEC = 5; - private static final int FAILURE_RECONNECT_ATTEMPTS = 3; - - // TODO move to payload of some sort - private final InetSocketAddress address; - - private final EventLoopGroup workerGroup = new NioEventLoopGroup(); - private final Bootstrap clientBootstrap = new Bootstrap() - .group(this.workerGroup) - .channel(NioSocketChannel.class) - .option(ChannelOption.SO_KEEPALIVE, true) - .handler(new NetworkChannelInitializer(this.messageHandler)); - - private EConnectionState connectionState; - private Channel channel; - private int reconnectAttempts = FAILURE_RECONNECT_ATTEMPTS; - - - - public NetworkClient(String host, int port) - { - this.address = new InetSocketAddress(host, port); - - this.registerHandlers(); - this.connect(); - } - - private void registerHandlers() - { - this.registerHandler(HelloMessage.class, (helloMessage, channelContext) -> - { - LOGGER.info("Connected to server: "+channelContext.channel().remoteAddress()); - }); - - this.registerHandler(CloseReasonMessage.class, (closeReasonMessage, channelContext) -> - { - LOGGER.info(closeReasonMessage.reason); - this.connectionState = EConnectionState.CLOSE_WAIT; - }); - - this.registerHandler(CloseMessage.class, (closeMessage, channelContext) -> - { - LOGGER.info("Disconnected from server: "+channelContext.channel().remoteAddress()); - if (this.connectionState == EConnectionState.CLOSE_WAIT) - { - this.close(); - } - }); - } - - private void connect() - { - LOGGER.info("Connecting to server: "+this.address); - this.connectionState = EConnectionState.OPEN; - - // FIXME sometimes this causes the MC connection to crash - // this might happen if the URL can't be converted to a IP (IE UnknownHostException) - ChannelFuture connectFuture = this.clientBootstrap.connect(this.address); - connectFuture.addListener((ChannelFuture channelFuture) -> - { - if (!channelFuture.isSuccess()) - { - LOGGER.warn("Connection failed: "+channelFuture.cause()); - return; - } - - this.channel.writeAndFlush(new HelloMessage()); - }); - - this.channel = connectFuture.channel(); - this. channel.closeFuture().addListener((ChannelFuture channelFuture) -> - { - switch (this.connectionState) - { - case OPEN: - this.reconnectAttempts--; - LOGGER.info("Reconnection attempts left: ["+this.reconnectAttempts+"] of ["+FAILURE_RECONNECT_ATTEMPTS+"]."); - if (this.reconnectAttempts == 0) - { - this.connectionState = EConnectionState.CLOSE_WAIT; - return; - } - - this.connectionState = EConnectionState.RECONNECT; - this.workerGroup.schedule(this::connect, FAILURE_RECONNECT_DELAY_SEC, TimeUnit.SECONDS); - break; - - case RECONNECT_FORCE: - LOGGER.info("Reconnecting forcefully."); - this.reconnectAttempts = FAILURE_RECONNECT_ATTEMPTS; - - this.connectionState = EConnectionState.RECONNECT; - this.workerGroup.schedule(this::connect, 0, TimeUnit.SECONDS); - break; - } - }); - } - - /** Kills the current connection, triggering auto-reconnection immediately. */ - public void reconnect() - { - this.connectionState = EConnectionState.RECONNECT_FORCE; - this.channel.disconnect(); - } - - @Override - public void close() - { - if (this.closeReason != null) - { - LOGGER.error(this.closeReason); - } - - if (this.connectionState == EConnectionState.CLOSED) - { - return; - } - - this.connectionState = EConnectionState.CLOSED; - this.workerGroup.shutdownGracefully().syncUninterruptibly(); - this.channel.close().syncUninterruptibly(); - } +// private static final Logger LOGGER = DhLoggerBuilder.getLogger(); +// +// private enum EConnectionState +// { +// OPEN, +// RECONNECT, +// RECONNECT_FORCE, +// CLOSE_WAIT, +// CLOSED +// } +// +// private static final int FAILURE_RECONNECT_DELAY_SEC = 5; +// private static final int FAILURE_RECONNECT_ATTEMPTS = 3; +// +// // TODO move to payload of some sort +// private final InetSocketAddress address; +// +// private final EventLoopGroup workerGroup = new NioEventLoopGroup(); +// private final Bootstrap clientBootstrap = new Bootstrap() +// .group(this.workerGroup) +// .channel(NioSocketChannel.class) +// .option(ChannelOption.SO_KEEPALIVE, true) +// .handler(new NetworkChannelInitializer(this.messageHandler)); +// +// private EConnectionState connectionState; +// private Channel channel; +// private int reconnectAttempts = FAILURE_RECONNECT_ATTEMPTS; +// +// +// +// public NetworkClient(String host, int port) +// { +// this.address = new InetSocketAddress(host, port); +// +// this.registerHandlers(); +// this.connect(); +// } +// +// private void registerHandlers() +// { +// this.registerHandler(HelloMessage.class, (helloMessage, channelContext) -> +// { +// LOGGER.info("Connected to server: "+channelContext.channel().remoteAddress()); +// }); +// +// this.registerHandler(CloseReasonMessage.class, (closeReasonMessage, channelContext) -> +// { +// LOGGER.info(closeReasonMessage.reason); +// this.connectionState = EConnectionState.CLOSE_WAIT; +// }); +// +// this.registerHandler(CloseMessage.class, (closeMessage, channelContext) -> +// { +// LOGGER.info("Disconnected from server: "+channelContext.channel().remoteAddress()); +// if (this.connectionState == EConnectionState.CLOSE_WAIT) +// { +// this.close(); +// } +// }); +// } +// +// private void connect() +// { +// LOGGER.info("Connecting to server: "+this.address); +// this.connectionState = EConnectionState.OPEN; +// +// // FIXME sometimes this causes the MC connection to crash +// // this might happen if the URL can't be converted to a IP (IE UnknownHostException) +// ChannelFuture connectFuture = this.clientBootstrap.connect(this.address); +// connectFuture.addListener((ChannelFuture channelFuture) -> +// { +// if (!channelFuture.isSuccess()) +// { +// LOGGER.warn("Connection failed: "+channelFuture.cause()); +// return; +// } +// +// this.channel.writeAndFlush(new HelloMessage()); +// }); +// +// this.channel = connectFuture.channel(); +// this. channel.closeFuture().addListener((ChannelFuture channelFuture) -> +// { +// switch (this.connectionState) +// { +// case OPEN: +// this.reconnectAttempts--; +// LOGGER.info("Reconnection attempts left: ["+this.reconnectAttempts+"] of ["+FAILURE_RECONNECT_ATTEMPTS+"]."); +// if (this.reconnectAttempts == 0) +// { +// this.connectionState = EConnectionState.CLOSE_WAIT; +// return; +// } +// +// this.connectionState = EConnectionState.RECONNECT; +// this.workerGroup.schedule(this::connect, FAILURE_RECONNECT_DELAY_SEC, TimeUnit.SECONDS); +// break; +// +// case RECONNECT_FORCE: +// LOGGER.info("Reconnecting forcefully."); +// this.reconnectAttempts = FAILURE_RECONNECT_ATTEMPTS; +// +// this.connectionState = EConnectionState.RECONNECT; +// this.workerGroup.schedule(this::connect, 0, TimeUnit.SECONDS); +// break; +// } +// }); +// } +// +// /** Kills the current connection, triggering auto-reconnection immediately. */ +// public void reconnect() +// { +// this.connectionState = EConnectionState.RECONNECT_FORCE; +// this.channel.disconnect(); +// } +// +// @Override +// public void close() +// { +// if (this.closeReason != null) +// { +// LOGGER.error(this.closeReason); +// } +// +// if (this.connectionState == EConnectionState.CLOSED) +// { +// return; +// } +// +// this.connectionState = EConnectionState.CLOSED; +// this.workerGroup.shutdownGracefully().syncUninterruptibly(); +// this.channel.close().syncUninterruptibly(); +// } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/NetworkEventSource.java b/core/src/main/java/com/seibel/distanthorizons/core/network/NetworkEventSource.java index f12967cb6..fd56c87fa 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/NetworkEventSource.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/NetworkEventSource.java @@ -6,7 +6,7 @@ import com.seibel.distanthorizons.core.network.messages.HelloMessage; import com.seibel.distanthorizons.core.network.protocol.INetworkMessage; import com.seibel.distanthorizons.core.network.protocol.MessageHandler; import com.seibel.distanthorizons.coreapi.ModInfo; -import io.netty.channel.ChannelHandlerContext; +//import io.netty.channel.ChannelHandlerContext; import org.apache.logging.log4j.Logger; import java.util.function.BiConsumer; @@ -21,43 +21,43 @@ public abstract class NetworkEventSource implements AutoCloseable - public NetworkEventSource() - { - this.registerHandler(HelloMessage.class, (helloMessage, channelContext) -> - { - if (helloMessage.version != ModInfo.PROTOCOL_VERSION) - { - try - { - String closeReason = "Ignoring message from channel ["+channelContext.name()+"], due to version mismatch. Expected version: ["+ModInfo.PROTOCOL_VERSION+"], received version: ["+helloMessage.version+"]."; - LOGGER.info(closeReason); - this.close(closeReason); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } - }); - } - - public void registerHandler(Class clazz, BiConsumer handler) { this.messageHandler.registerHandler(clazz, handler); } - - public void registerAckHandler(Class clazz, Consumer handler) - { - this.messageHandler.registerHandler(AckMessage.class, (ackMessage, channelContext) -> - { - if (ackMessage.messageType == clazz) - { - handler.accept(channelContext); - } - }); - } - - public void close(String reason) throws Exception - { - this.closeReason = reason; - this.close(); - } +// public NetworkEventSource() +// { +// this.registerHandler(HelloMessage.class, (helloMessage, channelContext) -> +// { +// if (helloMessage.version != ModInfo.PROTOCOL_VERSION) +// { +// try +// { +// String closeReason = "Ignoring message from channel ["+channelContext.name()+"], due to version mismatch. Expected version: ["+ModInfo.PROTOCOL_VERSION+"], received version: ["+helloMessage.version+"]."; +// LOGGER.info(closeReason); +// this.close(closeReason); +// } +// catch (Exception e) +// { +// throw new RuntimeException(e); +// } +// } +// }); +// } +// +// public void registerHandler(Class clazz, BiConsumer handler) { this.messageHandler.registerHandler(clazz, handler); } +// +// public void registerAckHandler(Class clazz, Consumer handler) +// { +// this.messageHandler.registerHandler(AckMessage.class, (ackMessage, channelContext) -> +// { +// if (ackMessage.messageType == clazz) +// { +// handler.accept(channelContext); +// } +// }); +// } +// +// public void close(String reason) throws Exception +// { +// this.closeReason = reason; +// this.close(); +// } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/NetworkServer.java b/core/src/main/java/com/seibel/distanthorizons/core/network/NetworkServer.java index b66e79879..971dce9ce 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/NetworkServer.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/NetworkServer.java @@ -5,99 +5,99 @@ import com.seibel.distanthorizons.core.network.messages.CloseReasonMessage; import com.seibel.distanthorizons.core.network.messages.CloseMessage; import com.seibel.distanthorizons.core.network.messages.HelloMessage; import com.seibel.distanthorizons.core.network.protocol.NetworkChannelInitializer; -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.*; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import io.netty.handler.logging.LogLevel; -import io.netty.handler.logging.LoggingHandler; +//import io.netty.bootstrap.ServerBootstrap; +//import io.netty.channel.*; +//import io.netty.channel.nio.NioEventLoopGroup; +//import io.netty.channel.socket.nio.NioServerSocketChannel; +//import io.netty.handler.logging.LogLevel; +//import io.netty.handler.logging.LoggingHandler; import org.apache.logging.log4j.Logger; -public class NetworkServer extends NetworkEventSource implements AutoCloseable +public class NetworkServer //extends NetworkEventSource implements AutoCloseable { - private static final Logger LOGGER = DhLoggerBuilder.getLogger(); - - // TODO move to the config - private final int port; - - private final EventLoopGroup bossGroup = new NioEventLoopGroup(1); - private final EventLoopGroup workerGroup = new NioEventLoopGroup(); - private Channel channel; - private boolean isClosed = false; - - - - public NetworkServer(int port) - { - this.port = port; - - LOGGER.info("Starting server on port "+port); - this.registerHandlers(); - this.bind(); - } - - private void registerHandlers() - { - this.registerHandler(HelloMessage.class, (helloMessage, channelContext) -> - { - LOGGER.info("Client connected: "+channelContext.channel().remoteAddress()); - channelContext.channel().writeAndFlush(new HelloMessage()); - }); - - this.registerHandler(CloseMessage.class, (closeMessage, channelContext) -> - { - LOGGER.info("Client disconnected: "+channelContext.channel().remoteAddress()); - }); - } - - private void bind() - { - ServerBootstrap bootstrap = new ServerBootstrap() - .group(this.bossGroup, this.workerGroup) - .channel(NioServerSocketChannel.class) - .handler(new LoggingHandler(LogLevel.DEBUG)) - .childHandler(new NetworkChannelInitializer(this.messageHandler)); - - ChannelFuture bindFuture = bootstrap.bind(this.port); - bindFuture.addListener((ChannelFuture channelFuture) -> - { - if (!channelFuture.isSuccess()) - { - throw new RuntimeException("Failed to bind: " + channelFuture.cause()); - } - - LOGGER.info("Server is started on port "+this.port); - }); - - this.channel = bindFuture.channel(); - this.channel.closeFuture().addListener(future -> this.close()); - } - - public void disconnectClient(ChannelHandlerContext ctx, String reason) - { - ctx.channel().config().setAutoRead(false); - ctx.writeAndFlush(new CloseReasonMessage(reason)) - .addListener(ChannelFutureListener.CLOSE); - } - - @Override - public void close() - { - if (this.closeReason != null) - { - LOGGER.error(this.closeReason); - } - - if (this.isClosed) - { - return; - } - this.isClosed = true; - - LOGGER.info("Shutting down the network server."); - this.workerGroup.shutdownGracefully().syncUninterruptibly(); - this.bossGroup.shutdownGracefully().syncUninterruptibly(); - LOGGER.info("Network server has been closed."); - } +// private static final Logger LOGGER = DhLoggerBuilder.getLogger(); +// +// // TODO move to the config +// private final int port; +// +// private final EventLoopGroup bossGroup = new NioEventLoopGroup(1); +// private final EventLoopGroup workerGroup = new NioEventLoopGroup(); +// private Channel channel; +// private boolean isClosed = false; +// +// +// +// public NetworkServer(int port) +// { +// this.port = port; +// +// LOGGER.info("Starting server on port "+port); +// this.registerHandlers(); +// this.bind(); +// } +// +// private void registerHandlers() +// { +// this.registerHandler(HelloMessage.class, (helloMessage, channelContext) -> +// { +// LOGGER.info("Client connected: "+channelContext.channel().remoteAddress()); +// channelContext.channel().writeAndFlush(new HelloMessage()); +// }); +// +// this.registerHandler(CloseMessage.class, (closeMessage, channelContext) -> +// { +// LOGGER.info("Client disconnected: "+channelContext.channel().remoteAddress()); +// }); +// } +// +// private void bind() +// { +// ServerBootstrap bootstrap = new ServerBootstrap() +// .group(this.bossGroup, this.workerGroup) +// .channel(NioServerSocketChannel.class) +// .handler(new LoggingHandler(LogLevel.DEBUG)) +// .childHandler(new NetworkChannelInitializer(this.messageHandler)); +// +// ChannelFuture bindFuture = bootstrap.bind(this.port); +// bindFuture.addListener((ChannelFuture channelFuture) -> +// { +// if (!channelFuture.isSuccess()) +// { +// throw new RuntimeException("Failed to bind: " + channelFuture.cause()); +// } +// +// LOGGER.info("Server is started on port "+this.port); +// }); +// +// this.channel = bindFuture.channel(); +// this.channel.closeFuture().addListener(future -> this.close()); +// } +// +// public void disconnectClient(ChannelHandlerContext ctx, String reason) +// { +// ctx.channel().config().setAutoRead(false); +// ctx.writeAndFlush(new CloseReasonMessage(reason)) +// .addListener(ChannelFutureListener.CLOSE); +// } +// +// @Override +// public void close() +// { +// if (this.closeReason != null) +// { +// LOGGER.error(this.closeReason); +// } +// +// if (this.isClosed) +// { +// return; +// } +// this.isClosed = true; +// +// LOGGER.info("Shutting down the network server."); +// this.workerGroup.shutdownGracefully().syncUninterruptibly(); +// this.bossGroup.shutdownGracefully().syncUninterruptibly(); +// LOGGER.info("Network server has been closed."); +// } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/AckMessage.java b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/AckMessage.java index a846352c7..b6d3a2811 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/AckMessage.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/AckMessage.java @@ -2,7 +2,7 @@ package com.seibel.distanthorizons.core.network.messages; import com.seibel.distanthorizons.core.network.protocol.INetworkMessage; import com.seibel.distanthorizons.core.network.protocol.MessageRegistry; -import io.netty.buffer.ByteBuf; +//import io.netty.buffer.ByteBuf; /** * Simple empty response message. @@ -17,10 +17,10 @@ public class AckMessage implements INetworkMessage public AckMessage() { } public AckMessage(Class messageType) { this.messageType = messageType; } - @Override - public void encode(ByteBuf out) { out.writeInt(MessageRegistry.INSTANCE.getMessageId(this.messageType)); } - - @Override - public void decode(ByteBuf in) { this.messageType = MessageRegistry.INSTANCE.getMessageClassById(in.readInt()); } +// @Override +// public void encode(ByteBuf out) { out.writeInt(MessageRegistry.INSTANCE.getMessageId(this.messageType)); } +// +// @Override +// public void decode(ByteBuf in) { this.messageType = MessageRegistry.INSTANCE.getMessageClassById(in.readInt()); } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/CloseMessage.java b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/CloseMessage.java index f42aa3515..4ced87800 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/CloseMessage.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/CloseMessage.java @@ -1,7 +1,7 @@ package com.seibel.distanthorizons.core.network.messages; import com.seibel.distanthorizons.core.network.protocol.INetworkMessage; -import io.netty.buffer.ByteBuf; +//import io.netty.buffer.ByteBuf; /** * This is not a "real" message, and only used to indicate a disconnection. @@ -9,11 +9,11 @@ import io.netty.buffer.ByteBuf; */ public class CloseMessage implements INetworkMessage { - @Override - public void encode(ByteBuf out) { throw new UnsupportedOperationException("CloseMessage is not a real message, and must not be sent."); } - - @Override - public void decode(ByteBuf in) { throw new UnsupportedOperationException("CloseMessage is not a real message, and must not be received."); } +// @Override +// public void encode(ByteBuf out) { throw new UnsupportedOperationException("CloseMessage is not a real message, and must not be sent."); } +// +// @Override +// public void decode(ByteBuf in) { throw new UnsupportedOperationException("CloseMessage is not a real message, and must not be received."); } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/CloseReasonMessage.java b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/CloseReasonMessage.java index 0671eb3c9..aa67d9bc9 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/CloseReasonMessage.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/CloseReasonMessage.java @@ -2,7 +2,7 @@ package com.seibel.distanthorizons.core.network.messages; import com.seibel.distanthorizons.core.network.protocol.INetworkMessage; import com.seibel.distanthorizons.core.network.protocol.INetworkObject; -import io.netty.buffer.ByteBuf; +//import io.netty.buffer.ByteBuf; public class CloseReasonMessage implements INetworkMessage { @@ -13,10 +13,10 @@ public class CloseReasonMessage implements INetworkMessage public CloseReasonMessage() { } public CloseReasonMessage(String reason) { this.reason = reason; } - @Override - public void encode(ByteBuf out) { INetworkObject.encodeString(this.reason, out); } - - @Override - public void decode(ByteBuf in) { this.reason = INetworkObject.decodeString(in); } +// @Override +// public void encode(ByteBuf out) { INetworkObject.encodeString(this.reason, out); } +// +// @Override +// public void decode(ByteBuf in) { this.reason = INetworkObject.decodeString(in); } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/HelloMessage.java b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/HelloMessage.java index 155f97dec..d2e0a9ca9 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/HelloMessage.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/HelloMessage.java @@ -2,7 +2,7 @@ package com.seibel.distanthorizons.core.network.messages; import com.seibel.distanthorizons.core.network.protocol.INetworkMessage; import com.seibel.distanthorizons.coreapi.ModInfo; -import io.netty.buffer.ByteBuf; +//import io.netty.buffer.ByteBuf; public class HelloMessage implements INetworkMessage { @@ -10,10 +10,10 @@ public class HelloMessage implements INetworkMessage - @Override - public void encode(ByteBuf out) { out.writeInt(this.version); } - - @Override - public void decode(ByteBuf in) { this.version = in.readInt(); } +// @Override +// public void encode(ByteBuf out) { out.writeInt(this.version); } +// +// @Override +// public void decode(ByteBuf in) { this.version = in.readInt(); } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/PlayerUUIDMessage.java b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/PlayerUUIDMessage.java index 09f15fd2c..b29e8608b 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/PlayerUUIDMessage.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/PlayerUUIDMessage.java @@ -1,7 +1,7 @@ package com.seibel.distanthorizons.core.network.messages; import com.seibel.distanthorizons.core.network.protocol.INetworkMessage; -import io.netty.buffer.ByteBuf; +//import io.netty.buffer.ByteBuf; import java.util.UUID; @@ -14,14 +14,14 @@ public class PlayerUUIDMessage implements INetworkMessage public PlayerUUIDMessage() { } public PlayerUUIDMessage(UUID playerUUID) { this.playerUUID = playerUUID; } - @Override - public void encode(ByteBuf out) - { - out.writeLong(this.playerUUID.getMostSignificantBits()); - out.writeLong(this.playerUUID.getLeastSignificantBits()); - } - - @Override - public void decode(ByteBuf in) { this.playerUUID = new UUID(in.readLong(), in.readLong()); } +// @Override +// public void encode(ByteBuf out) +// { +// out.writeLong(this.playerUUID.getMostSignificantBits()); +// out.writeLong(this.playerUUID.getLeastSignificantBits()); +// } +// +// @Override +// public void decode(ByteBuf in) { this.playerUUID = new UUID(in.readLong(), in.readLong()); } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/RemotePlayerConfigMessage.java b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/RemotePlayerConfigMessage.java index 8f0910801..fb278e6f3 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/RemotePlayerConfigMessage.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/RemotePlayerConfigMessage.java @@ -3,7 +3,7 @@ package com.seibel.distanthorizons.core.network.messages; import com.seibel.distanthorizons.core.network.protocol.INetworkObject; import com.seibel.distanthorizons.core.network.protocol.INetworkMessage; import com.seibel.distanthorizons.core.network.objects.RemotePlayer; -import io.netty.buffer.ByteBuf; +//import io.netty.buffer.ByteBuf; public class RemotePlayerConfigMessage implements INetworkMessage { @@ -14,10 +14,10 @@ public class RemotePlayerConfigMessage implements INetworkMessage public RemotePlayerConfigMessage() { } public RemotePlayerConfigMessage(RemotePlayer.Payload payload) { this.payload = payload; } - @Override - public void encode(ByteBuf out) { this.payload.encode(out); } - - @Override - public void decode(ByteBuf in) { this.payload = INetworkObject.decode(new RemotePlayer.Payload(), in); } +// @Override +// public void encode(ByteBuf out) { this.payload.encode(out); } +// +// @Override +// public void decode(ByteBuf in) { this.payload = INetworkObject.decode(new RemotePlayer.Payload(), in); } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/RequestChunksMessage.java b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/RequestChunksMessage.java index 15312601e..9f3745f2c 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/messages/RequestChunksMessage.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/messages/RequestChunksMessage.java @@ -1,21 +1,21 @@ package com.seibel.distanthorizons.core.network.messages; import com.seibel.distanthorizons.core.network.protocol.INetworkMessage; -import io.netty.buffer.ByteBuf; +//import io.netty.buffer.ByteBuf; public class RequestChunksMessage implements INetworkMessage { - @Override - public void encode(ByteBuf out) - { - - } - - @Override - public void decode(ByteBuf in) - { - - } +// @Override +// public void encode(ByteBuf out) +// { +// +// } +// +// @Override +// public void decode(ByteBuf in) +// { +// +// } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/objects/RemotePlayer.java b/core/src/main/java/com/seibel/distanthorizons/core/network/objects/RemotePlayer.java index 30f65397d..2b2bf751d 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/objects/RemotePlayer.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/objects/RemotePlayer.java @@ -2,14 +2,14 @@ package com.seibel.distanthorizons.core.network.objects; import com.seibel.distanthorizons.core.network.protocol.INetworkObject; import com.seibel.distanthorizons.core.wrapperInterfaces.misc.IServerPlayerWrapper; -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; +//import io.netty.buffer.ByteBuf; +//import io.netty.channel.ChannelHandlerContext; public class RemotePlayer { public IServerPlayerWrapper serverPlayer; public Payload payload; - public ChannelHandlerContext channelContext; +// public ChannelHandlerContext channelContext; @@ -23,11 +23,11 @@ public class RemotePlayer - @Override - public void encode(ByteBuf out) { out.writeInt(this.renderDistance); } - - @Override - public void decode(ByteBuf in) { this.renderDistance = in.readInt(); } +// @Override +// public void encode(ByteBuf out) { out.writeInt(this.renderDistance); } +// +// @Override +// public void decode(ByteBuf in) { this.renderDistance = in.readInt(); } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/INetworkObject.java b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/INetworkObject.java index 087e05b75..d76a79e11 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/INetworkObject.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/INetworkObject.java @@ -1,31 +1,31 @@ package com.seibel.distanthorizons.core.network.protocol; -import io.netty.buffer.ByteBuf; +//import io.netty.buffer.ByteBuf; import java.nio.charset.StandardCharsets; public interface INetworkObject { - void encode(ByteBuf out); - - void decode(ByteBuf in); - - static T decode(T obj, ByteBuf inputByteBuf) - { - obj.decode(inputByteBuf); - return obj; - } - - static void encodeString(String inputString, ByteBuf outputByteBuf) - { - outputByteBuf.writeShort(inputString.length()); - outputByteBuf.writeBytes(inputString.getBytes(StandardCharsets.UTF_8)); - } - - static String decodeString(ByteBuf inputByteBuf) - { - int length = inputByteBuf.readShort(); - return inputByteBuf.readBytes(length).toString(StandardCharsets.UTF_8); - } +// void encode(ByteBuf out); +// +// void decode(ByteBuf in); +// +// static T decode(T obj, ByteBuf inputByteBuf) +// { +// obj.decode(inputByteBuf); +// return obj; +// } +// +// static void encodeString(String inputString, ByteBuf outputByteBuf) +// { +// outputByteBuf.writeShort(inputString.length()); +// outputByteBuf.writeBytes(inputString.getBytes(StandardCharsets.UTF_8)); +// } +// +// static String decodeString(ByteBuf inputByteBuf) +// { +// int length = inputByteBuf.readShort(); +// return inputByteBuf.readBytes(length).toString(StandardCharsets.UTF_8); +// } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/MessageDecoder.java b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/MessageDecoder.java index 19eb98722..41c832fec 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/MessageDecoder.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/MessageDecoder.java @@ -1,18 +1,18 @@ package com.seibel.distanthorizons.core.network.protocol; -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageDecoder; +//import io.netty.buffer.ByteBuf; +//import io.netty.channel.ChannelHandlerContext; +//import io.netty.handler.codec.ByteToMessageDecoder; import java.util.List; -public class MessageDecoder extends ByteToMessageDecoder +public class MessageDecoder //extends ByteToMessageDecoder { - @Override - protected void decode(ChannelHandlerContext channelContext, ByteBuf inputByteBuf, List outputDecodedObjectList) - { - INetworkMessage message = MessageRegistry.INSTANCE.createMessage(inputByteBuf.readShort()); - outputDecodedObjectList.add(INetworkObject.decode(message, inputByteBuf)); - } +// @Override +// protected void decode(ChannelHandlerContext channelContext, ByteBuf inputByteBuf, List outputDecodedObjectList) +// { +// INetworkMessage message = MessageRegistry.INSTANCE.createMessage(inputByteBuf.readShort()); +// outputDecodedObjectList.add(INetworkObject.decode(message, inputByteBuf)); +// } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/MessageEncoder.java b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/MessageEncoder.java index ddb7ed5f3..5b08cd6bd 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/MessageEncoder.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/MessageEncoder.java @@ -1,16 +1,16 @@ package com.seibel.distanthorizons.core.network.protocol; -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; +//import io.netty.buffer.ByteBuf; +//import io.netty.channel.ChannelHandlerContext; +//import io.netty.handler.codec.MessageToByteEncoder; -public class MessageEncoder extends MessageToByteEncoder +public class MessageEncoder //extends MessageToByteEncoder { - @Override - protected void encode(ChannelHandlerContext channelContext, INetworkMessage message, ByteBuf outputByteBuf) throws IllegalArgumentException - { - outputByteBuf.writeShort(MessageRegistry.INSTANCE.getMessageId(message)); - message.encode(outputByteBuf); - } +// @Override +// protected void encode(ChannelHandlerContext channelContext, INetworkMessage message, ByteBuf outputByteBuf) throws IllegalArgumentException +// { +// outputByteBuf.writeShort(MessageRegistry.INSTANCE.getMessageId(message)); +// message.encode(outputByteBuf); +// } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/MessageHandler.java b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/MessageHandler.java index 9fc9626d2..d525b8003 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/MessageHandler.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/MessageHandler.java @@ -2,9 +2,9 @@ package com.seibel.distanthorizons.core.network.protocol; import com.seibel.distanthorizons.core.logging.DhLoggerBuilder; import com.seibel.distanthorizons.core.network.messages.CloseMessage; -import io.netty.channel.ChannelHandler; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; +//import io.netty.channel.ChannelHandler; +//import io.netty.channel.ChannelHandlerContext; +//import io.netty.channel.SimpleChannelInboundHandler; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; @@ -14,40 +14,40 @@ import java.util.List; import java.util.Map; import java.util.function.BiConsumer; -@ChannelHandler.Sharable -public class MessageHandler extends SimpleChannelInboundHandler +//@ChannelHandler.Sharable +public class MessageHandler //extends SimpleChannelInboundHandler { - private static final Logger LOGGER = DhLoggerBuilder.getLogger(); - - private final Map, List>> handlers = new HashMap<>(); - - - - public void registerHandler(Class handlerClass, BiConsumer handlerImplementation) - { - this.handlers.computeIfAbsent(handlerClass, missingHandlerClass -> new LinkedList<>()) - .add((BiConsumer) handlerImplementation); - } - - @Override - protected void channelRead0(ChannelHandlerContext channelContext, INetworkMessage message) - { - LOGGER.trace("Received message: "+message.getClass().getSimpleName()); - - List> handlerList = this.handlers.get(message.getClass()); - if (handlerList == null) - { - LOGGER.warn("Unhandled message type: "+message.getClass().getSimpleName()); - return; - } - - for (BiConsumer handler : handlerList) - { - handler.accept(message, channelContext); - } - } - - @Override - public void channelInactive(@NotNull ChannelHandlerContext channelContext) { this.channelRead0(channelContext, new CloseMessage()); } +// private static final Logger LOGGER = DhLoggerBuilder.getLogger(); +// +// private final Map, List>> handlers = new HashMap<>(); +// +// +// +// public void registerHandler(Class handlerClass, BiConsumer handlerImplementation) +// { +// this.handlers.computeIfAbsent(handlerClass, missingHandlerClass -> new LinkedList<>()) +// .add((BiConsumer) handlerImplementation); +// } +// +// @Override +// protected void channelRead0(ChannelHandlerContext channelContext, INetworkMessage message) +// { +// LOGGER.trace("Received message: "+message.getClass().getSimpleName()); +// +// List> handlerList = this.handlers.get(message.getClass()); +// if (handlerList == null) +// { +// LOGGER.warn("Unhandled message type: "+message.getClass().getSimpleName()); +// return; +// } +// +// for (BiConsumer handler : handlerList) +// { +// handler.accept(message, channelContext); +// } +// } +// +// @Override +// public void channelInactive(@NotNull ChannelHandlerContext channelContext) { this.channelRead0(channelContext, new CloseMessage()); } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/NetworkChannelInitializer.java b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/NetworkChannelInitializer.java index f021396b6..52fe4fe77 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/NetworkChannelInitializer.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/NetworkChannelInitializer.java @@ -1,13 +1,13 @@ package com.seibel.distanthorizons.core.network.protocol; -import io.netty.channel.*; -import io.netty.channel.socket.SocketChannel; -import io.netty.handler.codec.LengthFieldBasedFrameDecoder; -import io.netty.handler.codec.LengthFieldPrepender; +//import io.netty.channel.*; +//import io.netty.channel.socket.SocketChannel; +//import io.netty.handler.codec.LengthFieldBasedFrameDecoder; +//import io.netty.handler.codec.LengthFieldPrepender; import org.jetbrains.annotations.NotNull; /** used when creating a network channel */ -public class NetworkChannelInitializer extends ChannelInitializer +public class NetworkChannelInitializer //extends ChannelInitializer { private final MessageHandler messageHandler; @@ -15,23 +15,23 @@ public class NetworkChannelInitializer extends ChannelInitializer public NetworkChannelInitializer(MessageHandler messageHandler) { this.messageHandler = messageHandler; } - @Override - public void initChannel(@NotNull SocketChannel socketChannel) - { - ChannelPipeline pipeline = socketChannel.pipeline(); - - // Encoder - pipeline.addLast(new LengthFieldPrepender(Short.BYTES)); - pipeline.addLast(new MessageEncoder()); - pipeline.addLast(new NetworkOutboundExceptionRouter()); - - // Decoder - pipeline.addLast(new LengthFieldBasedFrameDecoder(Short.MAX_VALUE, 0, Short.BYTES, 0, Short.BYTES)); - pipeline.addLast(new MessageDecoder()); - - // Handler - pipeline.addLast(this.messageHandler); - pipeline.addLast(new NetworkExceptionHandler()); - } - +// @Override +// public void initChannel(@NotNull SocketChannel socketChannel) +// { +// ChannelPipeline pipeline = socketChannel.pipeline(); +// +// // Encoder +// pipeline.addLast(new LengthFieldPrepender(Short.BYTES)); +// pipeline.addLast(new MessageEncoder()); +// pipeline.addLast(new NetworkOutboundExceptionRouter()); +// +// // Decoder +// pipeline.addLast(new LengthFieldBasedFrameDecoder(Short.MAX_VALUE, 0, Short.BYTES, 0, Short.BYTES)); +// pipeline.addLast(new MessageDecoder()); +// +// // Handler +// pipeline.addLast(this.messageHandler); +// pipeline.addLast(new NetworkExceptionHandler()); +// } +// } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/NetworkExceptionHandler.java b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/NetworkExceptionHandler.java index 365e0e434..5b44e44da 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/NetworkExceptionHandler.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/NetworkExceptionHandler.java @@ -1,19 +1,19 @@ package com.seibel.distanthorizons.core.network.protocol; import com.seibel.distanthorizons.core.logging.DhLoggerBuilder; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; +//import io.netty.channel.ChannelHandlerContext; +//import io.netty.channel.ChannelInboundHandlerAdapter; import org.apache.logging.log4j.Logger; -public class NetworkExceptionHandler extends ChannelInboundHandlerAdapter +public class NetworkExceptionHandler //extends ChannelInboundHandlerAdapter { private static final Logger LOGGER = DhLoggerBuilder.getLogger(); - @Override - public void exceptionCaught(ChannelHandlerContext channelContext, Throwable cause) - { - LOGGER.error("Exception caught in channel: ["+channelContext.name()+"].", cause); - channelContext.close(); - } +// @Override +// public void exceptionCaught(ChannelHandlerContext channelContext, Throwable cause) +// { +// LOGGER.error("Exception caught in channel: ["+channelContext.name()+"].", cause); +// channelContext.close(); +// } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/NetworkOutboundExceptionRouter.java b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/NetworkOutboundExceptionRouter.java index dee8614e8..138e12706 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/NetworkOutboundExceptionRouter.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/network/protocol/NetworkOutboundExceptionRouter.java @@ -1,17 +1,17 @@ package com.seibel.distanthorizons.core.network.protocol; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelOutboundHandlerAdapter; -import io.netty.channel.ChannelPromise; +//import io.netty.channel.ChannelFutureListener; +//import io.netty.channel.ChannelHandlerContext; +//import io.netty.channel.ChannelOutboundHandlerAdapter; +//import io.netty.channel.ChannelPromise; -public class NetworkOutboundExceptionRouter extends ChannelOutboundHandlerAdapter +public class NetworkOutboundExceptionRouter //extends ChannelOutboundHandlerAdapter { - @Override - public void write(ChannelHandlerContext channelContext, Object messageObj, ChannelPromise promise) throws Exception - { - promise.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); - super.write(channelContext, messageObj, promise); - } +// @Override +// public void write(ChannelHandlerContext channelContext, Object messageObj, ChannelPromise promise) throws Exception +// { +// promise.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); +// super.write(channelContext, messageObj, promise); +// } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/world/DhClientWorld.java b/core/src/main/java/com/seibel/distanthorizons/core/world/DhClientWorld.java index bed9ea75c..fc1341bbb 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/world/DhClientWorld.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/world/DhClientWorld.java @@ -28,7 +28,7 @@ public class DhClientWorld extends AbstractDhWorld implements IDhClientWorld private final ConcurrentHashMap levels; public final ClientOnlySaveStructure saveStructure; - private final NetworkClient networkClient; +// private final NetworkClient networkClient; // TODO why does this executor have 2 threads? public ExecutorService dhTickerThread = ThreadUtil.makeSingleThreadPool("DH Client World Ticker Thread", 2); @@ -50,12 +50,12 @@ public class DhClientWorld extends AbstractDhWorld implements IDhClientWorld if (Config.Client.Advanced.Multiplayer.enableServerNetworking.get()) { // TODO server specific configs - this.networkClient = new NetworkClient(MC_CLIENT.getCurrentServerIp(), 25049); +// this.networkClient = new NetworkClient(MC_CLIENT.getCurrentServerIp(), 25049); this.registerNetworkHandlers(); } else { - this.networkClient = null; +// this.networkClient = null; } LOGGER.info("Started DhWorld of type "+this.environment); @@ -63,26 +63,26 @@ public class DhClientWorld extends AbstractDhWorld implements IDhClientWorld private void registerNetworkHandlers() { - this.networkClient.registerHandler(HelloMessage.class, (msg, ctx) -> - { - ctx.writeAndFlush(new PlayerUUIDMessage(MC_CLIENT.getPlayerUUID())); - }); - - // TODO Proper payload handling - this.networkClient.registerAckHandler(PlayerUUIDMessage.class, ctx -> - { - ctx.writeAndFlush(new RemotePlayerConfigMessage(new RemotePlayer.Payload())); - }); - this.networkClient.registerHandler(RemotePlayerConfigMessage.class, (msg, ctx) -> - { - - }); - - this.networkClient.registerAckHandler(RemotePlayerConfigMessage.class, ctx -> - { - // TODO Actually request chunks - ctx.writeAndFlush(new RequestChunksMessage()); - }); +// this.networkClient.registerHandler(HelloMessage.class, (msg, ctx) -> +// { +// ctx.writeAndFlush(new PlayerUUIDMessage(MC_CLIENT.getPlayerUUID())); +// }); +// +// // TODO Proper payload handling +// this.networkClient.registerAckHandler(PlayerUUIDMessage.class, ctx -> +// { +// ctx.writeAndFlush(new RemotePlayerConfigMessage(new RemotePlayer.Payload())); +// }); +// this.networkClient.registerHandler(RemotePlayerConfigMessage.class, (msg, ctx) -> +// { +// +// }); +// +// this.networkClient.registerAckHandler(RemotePlayerConfigMessage.class, ctx -> +// { +// // TODO Actually request chunks +// ctx.writeAndFlush(new RequestChunksMessage()); +// }); } @@ -157,10 +157,10 @@ public class DhClientWorld extends AbstractDhWorld implements IDhClientWorld @Override public void close() { - if (this.networkClient != null) - { - this.networkClient.close(); - } +// if (this.networkClient != null) +// { +//// this.networkClient.close(); +// } this.saveAndFlush(); diff --git a/core/src/main/java/com/seibel/distanthorizons/core/world/DhServerWorld.java b/core/src/main/java/com/seibel/distanthorizons/core/world/DhServerWorld.java index dbbea1b33..1fdb28abb 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/world/DhServerWorld.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/world/DhServerWorld.java @@ -13,7 +13,7 @@ import com.seibel.distanthorizons.core.util.LodUtil; import com.seibel.distanthorizons.core.wrapperInterfaces.misc.IServerPlayerWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IServerLevelWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.ILevelWrapper; -import io.netty.channel.ChannelHandlerContext; +//import io.netty.channel.ChannelHandlerContext; import java.io.File; import java.util.HashMap; @@ -25,9 +25,9 @@ public class DhServerWorld extends AbstractDhWorld implements IDhServerWorld private final HashMap levels; public final LocalSaveStructure saveStructure; - private final NetworkServer networkServer; - private final HashMap playersByUUID; - private final BiMap playersByConnection; +// private final NetworkServer networkServer; +// private final HashMap playersByUUID; +// private final BiMap playersByConnection; @@ -39,73 +39,73 @@ public class DhServerWorld extends AbstractDhWorld implements IDhServerWorld this.levels = new HashMap<>(); // TODO move to global payload once server specific configs are implemented - this.networkServer = new NetworkServer(25049); - this.playersByUUID = new HashMap<>(); - this.playersByConnection = HashBiMap.create(); - this.registerNetworkHandlers(); +// this.networkServer = new NetworkServer(25049); +// this.playersByUUID = new HashMap<>(); +// this.playersByConnection = HashBiMap.create(); +// this.registerNetworkHandlers(); LOGGER.info("Started "+DhServerWorld.class.getSimpleName()+" of type "+this.environment); } private void registerNetworkHandlers() { - this.networkServer.registerHandler(CloseMessage.class, (closeMessage, channelContext) -> - { - RemotePlayer dhPlayer = this.playersByConnection.remove(channelContext); - if (dhPlayer != null) - { - dhPlayer.channelContext = null; - } - }); - - this.networkServer.registerHandler(PlayerUUIDMessage.class, (playerUUIDMessage, channelContext) -> - { - RemotePlayer dhPlayer = this.playersByUUID.get(playerUUIDMessage.playerUUID); - - if (dhPlayer == null) - { - this.networkServer.disconnectClient(channelContext, "Player is not logged in."); - return; - } - - if (dhPlayer.channelContext != null) - { - this.networkServer.disconnectClient(channelContext, "Another connection is already in use."); - return; - } - - dhPlayer.channelContext = channelContext; - this.playersByConnection.put(channelContext, dhPlayer); - - channelContext.writeAndFlush(new AckMessage(PlayerUUIDMessage.class)); - }); - - this.networkServer.registerHandler(RemotePlayerConfigMessage.class, (dhRemotePlayerConfigMessage, channelContext) -> - { - // TODO Take notice of received payload and possibly echo back a constrained version - channelContext.writeAndFlush(new AckMessage(RemotePlayerConfigMessage.class)); - }); - - this.networkServer.registerHandler(RequestChunksMessage.class, (msg, ctx) -> - { - LOGGER.info("RequestChunksMessage"); - // hasReceivedChunkRequest should be false somewhere ??? - // to avoid sending updates until client says at least something about its state - }); +// this.networkServer.registerHandler(CloseMessage.class, (closeMessage, channelContext) -> +// { +// RemotePlayer dhPlayer = this.playersByConnection.remove(channelContext); +// if (dhPlayer != null) +// { +// dhPlayer.channelContext = null; +// } +// }); +// +// this.networkServer.registerHandler(PlayerUUIDMessage.class, (playerUUIDMessage, channelContext) -> +// { +// RemotePlayer dhPlayer = this.playersByUUID.get(playerUUIDMessage.playerUUID); +// +// if (dhPlayer == null) +// { +// this.networkServer.disconnectClient(channelContext, "Player is not logged in."); +// return; +// } +// +// if (dhPlayer.channelContext != null) +// { +// this.networkServer.disconnectClient(channelContext, "Another connection is already in use."); +// return; +// } +// +// dhPlayer.channelContext = channelContext; +// this.playersByConnection.put(channelContext, dhPlayer); +// +// channelContext.writeAndFlush(new AckMessage(PlayerUUIDMessage.class)); +// }); +// +// this.networkServer.registerHandler(RemotePlayerConfigMessage.class, (dhRemotePlayerConfigMessage, channelContext) -> +// { +// // TODO Take notice of received payload and possibly echo back a constrained version +// channelContext.writeAndFlush(new AckMessage(RemotePlayerConfigMessage.class)); +// }); +// +// this.networkServer.registerHandler(RequestChunksMessage.class, (msg, ctx) -> +// { +// LOGGER.info("RequestChunksMessage"); +// // hasReceivedChunkRequest should be false somewhere ??? +// // to avoid sending updates until client says at least something about its state +// }); } public void addPlayer(IServerPlayerWrapper serverPlayer) { - this.playersByUUID.put(serverPlayer.getUUID(), new RemotePlayer(serverPlayer)); + //this.playersByUUID.put(serverPlayer.getUUID(), new RemotePlayer(serverPlayer)); } public void removePlayer(IServerPlayerWrapper serverPlayer) { - RemotePlayer dhPlayer = this.playersByUUID.remove(serverPlayer.getUUID()); - ChannelHandlerContext channelContext = this.playersByConnection.inverse().remove(dhPlayer); - if (channelContext != null) - { - this.networkServer.disconnectClient(channelContext, "You are being disconnected."); - } +// RemotePlayer dhPlayer = this.playersByUUID.remove(serverPlayer.getUUID()); +// ChannelHandlerContext channelContext = this.playersByConnection.inverse().remove(dhPlayer); +// if (channelContext != null) +// { +// this.networkServer.disconnectClient(channelContext, "You are being disconnected."); +// } } @Override @@ -166,7 +166,7 @@ public class DhServerWorld extends AbstractDhWorld implements IDhServerWorld @Override public void close() { - this.networkServer.close(); +// this.networkServer.close(); for (DhServerLevel level : this.levels.values()) { From 8bcfe3e35d51ca162382308818206206a2072787 Mon Sep 17 00:00:00 2001 From: James Seibel Date: Sat, 5 Aug 2023 22:25:06 -0500 Subject: [PATCH 11/24] Increment Full Data Source version 1 -> 2 Done due to serialization changes --- .../dataObjects/fullData/sources/CompleteFullDataSource.java | 2 +- .../fullData/sources/HighDetailIncompleteFullDataSource.java | 2 +- .../fullData/sources/LowDetailIncompleteFullDataSource.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/fullData/sources/CompleteFullDataSource.java b/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/fullData/sources/CompleteFullDataSource.java index 98b7bf8bf..7e3cda75e 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/fullData/sources/CompleteFullDataSource.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/fullData/sources/CompleteFullDataSource.java @@ -37,7 +37,7 @@ public class CompleteFullDataSource extends FullDataArrayAccessor implements IFu /** measured in dataPoints */ public static final int WIDTH = BitShiftUtil.powerOfTwo(SECTION_SIZE_OFFSET); - public static final byte DATA_FORMAT_VERSION = 1; + public static final byte DATA_FORMAT_VERSION = 2; /** written to the binary file to mark what {@link IFullDataSource} the binary file corresponds to */ public static final long TYPE_ID = "CompleteFullDataSource".hashCode(); diff --git a/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/fullData/sources/HighDetailIncompleteFullDataSource.java b/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/fullData/sources/HighDetailIncompleteFullDataSource.java index 6b67c65ad..5b12f6ed2 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/fullData/sources/HighDetailIncompleteFullDataSource.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/fullData/sources/HighDetailIncompleteFullDataSource.java @@ -51,7 +51,7 @@ public class HighDetailIncompleteFullDataSource implements IIncompleteFullDataSo /** aka max detail level */ public static final byte MAX_SECTION_DETAIL = SECTION_SIZE_OFFSET + SPARSE_UNIT_DETAIL; - public static final byte DATA_FORMAT_VERSION = 1; + public static final byte DATA_FORMAT_VERSION = 2; /** written to the binary file to mark what {@link IFullDataSource} the binary file corresponds to */ public static final long TYPE_ID = "HighDetailIncompleteFullDataSource".hashCode(); diff --git a/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/fullData/sources/LowDetailIncompleteFullDataSource.java b/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/fullData/sources/LowDetailIncompleteFullDataSource.java index 25de2c369..e8ab5cc75 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/fullData/sources/LowDetailIncompleteFullDataSource.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/dataObjects/fullData/sources/LowDetailIncompleteFullDataSource.java @@ -42,7 +42,7 @@ public class LowDetailIncompleteFullDataSource extends FullDataArrayAccessor imp /** measured in dataPoints */ public static final int WIDTH = BitShiftUtil.powerOfTwo(SECTION_SIZE_OFFSET); - public static final byte DATA_FORMAT_VERSION = 1; + public static final byte DATA_FORMAT_VERSION = 2; /** written to the binary file to mark what {@link IFullDataSource} the binary file corresponds to */ public static final long TYPE_ID = "LowDetailIncompleteFullDataSource".hashCode(); From b53739a112ee451c9324781efc3c5a24fb607c2e Mon Sep 17 00:00:00 2001 From: James Seibel Date: Sat, 5 Aug 2023 22:33:30 -0500 Subject: [PATCH 12/24] Comment out a couple missed Netty lines --- .../java/com/seibel/distanthorizons/core/Initializer.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/Initializer.java b/core/src/main/java/com/seibel/distanthorizons/core/Initializer.java index a580e8d2a..cb4e4512d 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/Initializer.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/Initializer.java @@ -9,7 +9,7 @@ import com.seibel.distanthorizons.core.dataObjects.fullData.loader.HighDetailInc import com.seibel.distanthorizons.api.DhApi; import com.seibel.distanthorizons.core.dataObjects.fullData.loader.LowDetailIncompleteFullDataSourceLoader; import com.seibel.distanthorizons.core.render.DhApiRenderProxy; -import io.netty.buffer.ByteBuf; +//import io.netty.buffer.ByteBuf; import net.jpountz.lz4.LZ4Compressor; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -27,7 +27,7 @@ public class Initializer // if any library isn't present in the jar its class // will throw an error (not an exception) Class compressor = LZ4Compressor.class; - Class networking = ByteBuf.class; + //Class networking = ByteBuf.class; Class toml = com.electronwill.nightconfig.core.Config.class; Class flatlaf = com.formdev.flatlaf.FlatDarculaLaf.class; } From 7ccb5c180618cf777f59866e847528379ab72fea Mon Sep 17 00:00:00 2001 From: coolGi Date: Sun, 6 Aug 2023 17:15:17 +0930 Subject: [PATCH 13/24] Added white world option --- .../com/seibel/distanthorizons/core/config/Config.java | 7 +++++++ .../core/render/renderer/LodRenderProgram.java | 10 ++++++++++ .../resources/assets/distanthorizons/lang/en_us.json | 6 +++++- core/src/main/resources/shaders/standard.vert | 6 +++++- 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java b/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java index 67b759294..49b63638b 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java @@ -1081,6 +1081,13 @@ public class Config + " will render their debug wireframes.") .build(); + public static ConfigEntry enableWhiteWorld = new ConfigEntry.Builder() + .set(false) + .comment("" + + "Stops vertex colors from being passed. \n" + + "Useful for debugging shaders") + .build(); + // Note: This will reset on game restart, and should have a warning on the tooltip public static ConfigEntry allowUnsafeValues = new ConfigEntry.Builder() .set(false) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java index cecf49059..595ab0d4f 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderProgram.java @@ -21,6 +21,7 @@ package com.seibel.distanthorizons.core.render.renderer; import java.awt.Color; +import com.seibel.distanthorizons.core.config.Config; import com.seibel.distanthorizons.core.dependencyInjection.SingletonInjector; import com.seibel.distanthorizons.core.render.glObject.GLProxy; import com.seibel.distanthorizons.core.render.glObject.shader.Shader; @@ -68,6 +69,9 @@ public class LodRenderProgram extends ShaderProgram public final int noiseIntensityUniform; public final int noiseDropoffUniform; + // Debug Uniform + public final int whiteWorldUniform; + public final LodFogConfig fogConfig; // This will bind VertexAttribute @@ -101,6 +105,9 @@ public class LodRenderProgram extends ShaderProgram noiseIntensityUniform = getUniformLocation("noiseIntensity"); noiseDropoffUniform = getUniformLocation("noiseDropoff"); + // Debug Uniform + whiteWorldUniform = getUniformLocation("whiteWorld"); + // TODO: Add better use of the LODFormat thing int vertexByteCount = LodUtil.LOD_VERTEX_FORMAT.getByteSize(); @@ -181,6 +188,9 @@ public class LodRenderProgram extends ShaderProgram setUniform(fullFogModeUniform, fullFogMode ? 1 : 0); setUniform(fogColorUniform, fogColor); + // Debug + setUniform(whiteWorldUniform, Config.Client.Advanced.Debugging.enableWhiteWorld.get()); + float nearFogLen = vanillaDrawDistance * 0.2f / lodDrawDistance; float nearFogStart = vanillaDrawDistance * (VERSION_CONSTANTS.isVanillaRenderedChunkSquare() ? (float)Math.sqrt(2.) : 1.f) / lodDrawDistance; if (nearFogStartUniform != -1) setUniform(nearFogStartUniform, nearFogStart); diff --git a/core/src/main/resources/assets/distanthorizons/lang/en_us.json b/core/src/main/resources/assets/distanthorizons/lang/en_us.json index 1bdabf28d..2120be320 100644 --- a/core/src/main/resources/assets/distanthorizons/lang/en_us.json +++ b/core/src/main/resources/assets/distanthorizons/lang/en_us.json @@ -379,7 +379,11 @@ "distanthorizons.config.client.advanced.debugging.debugWireframeRendering": "Enable Debug Wireframe Rendering", "distanthorizons.config.client.advanced.debugging.debugWireframeRendering.@tooltip": - "If enabled, various wireframes for debugging internal functions will be drawn.", + "If enabled, various wireframes for debugging internal functions will be drawn.", + "distanthorizons.config.client.advanced.debugging.enableWhiteWorld": + "Enable white world", + "distanthorizons.config.client.advanced.debugging.enableWhiteWorld.@tooltip": + "If enabled, vertex color will not be passed.\nUseful for debugging shaders.", "distanthorizons.config.client.advanced.debugging.allowUnsafeValues": "Allow Unsafe UI Values", "distanthorizons.config.client.advanced.debugging.allowUnsafeValues.@tooltip": diff --git a/core/src/main/resources/shaders/standard.vert b/core/src/main/resources/shaders/standard.vert index 88904a744..ffa41f9db 100644 --- a/core/src/main/resources/shaders/standard.vert +++ b/core/src/main/resources/shaders/standard.vert @@ -8,6 +8,8 @@ out vec4 vertexColor; out vec3 vertexWorldPos; out float vertexYPos; +uniform bool whiteWorld; + uniform mat4 combinedMatrix; uniform vec3 modelOffset; uniform float worldYOffset; @@ -51,7 +53,9 @@ void main() float light2 = (mod(float(lights), 16.0)+0.5) / 16.0; float light = (float(lights/16u)+0.5) / 16.0; - vertexColor = color * vec4(texture(lightMap, vec2(light, light2)).xyz, 1.0); + vertexColor = vec4(texture(lightMap, vec2(light, light2)).xyz, 1.0); + if (!whiteWorld) + vertexColor *= color; gl_Position = combinedMatrix * vec4(vertexWorldPos + vec3(mx, 0, mz), 1.0); } From 475e4da4a7beb2dcac0a026867d65a8879f899c0 Mon Sep 17 00:00:00 2001 From: coolGi Date: Sun, 6 Aug 2023 17:30:27 +0930 Subject: [PATCH 14/24] Removed config entries from checking their own types as its already done in the config base --- .../core/config/file/ConfigFileHandling.java | 2 ++ .../core/config/types/ConfigEntry.java | 28 +------------------ 2 files changed, 3 insertions(+), 27 deletions(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/file/ConfigFileHandling.java b/core/src/main/java/com/seibel/distanthorizons/core/config/file/ConfigFileHandling.java index 270ecda4c..83910c4ee 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/config/file/ConfigFileHandling.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/config/file/ConfigFileHandling.java @@ -112,6 +112,8 @@ public class ConfigFileHandling { @SuppressWarnings("unchecked") public void saveEntry(ConfigEntry entry, CommentedFileConfig workConfig) { if (!entry.getAppearance().showInFile) return; + if (entry.getTrueValue() == null) + throw new IllegalArgumentException("Entry ["+ entry.getNameWCategory() +"] is null, this may be a problem with ["+ configBase.modName +"]. Please contact the authors"); if (ConfigTypeConverters.convertObjects.containsKey(entry.getType())) { workConfig.set(entry.getNameWCategory(), ConfigTypeConverters.convertToString(entry.getType(), entry.getTrueValue())); diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigEntry.java b/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigEntry.java index 4d1908490..218aacbd3 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigEntry.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigEntry.java @@ -7,12 +7,8 @@ import com.seibel.distanthorizons.core.config.types.enums.EConfigEntryAppearance import com.seibel.distanthorizons.core.config.types.enums.EConfigEntryPerformance; import com.seibel.distanthorizons.coreapi.interfaces.config.IConfigEntry; -import java.time.temporal.Temporal; import java.util.ArrayList; import java.util.Arrays; -import java.util.List; - -import static com.electronwill.nightconfig.core.NullObject.NULL_OBJECT; /** * Use for making the config variables @@ -44,29 +40,7 @@ public class ConfigEntry extends AbstractConfigType> implem private ConfigEntry(EConfigEntryAppearance appearance, T value, String comment, T min, T max, boolean allowApiOverride, EConfigEntryPerformance performance, ArrayList listenerList) { super(appearance, value); - - // runtime check to make sure the config value is supported by NightConfig, - // unfortunately we can't do this type of check statically without Java 16 - if (value == null) - { - throw new IllegalArgumentException("ConfigEntry setup failure. TOML doesn't support saving null values."); - } - // all of these types were taken from NightConfig's writing code - else if (!(value instanceof List) - && !(value instanceof CharSequence) // String - && !(value instanceof Enum) - && !(value instanceof Temporal) // Date or DateTime - && !(value instanceof Float || value instanceof Double) - && !(value instanceof Number) - && !(value instanceof Boolean) - // optional type that is specific to NightConfig, currently commented out so we aren't tied quite so tightly to NightConfig - //&& !(value instanceof Config) // NightConfig interface - ) - { - throw new IllegalArgumentException("ConfigEntry setup failure. Value type ["+value.getClass()+"] is not supported by NightConfig."); - } - - + this.defaultValue = value; this.comment = comment; this.min = min; From e5dcc4189d73011269a25564ba889459b2a10bac Mon Sep 17 00:00:00 2001 From: coolGi Date: Sun, 6 Aug 2023 18:56:16 +0930 Subject: [PATCH 15/24] Fixed bug with updater giving invalid update checksum --- .../core/jar/installer/ModrinthGetter.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/jar/installer/ModrinthGetter.java b/core/src/main/java/com/seibel/distanthorizons/core/jar/installer/ModrinthGetter.java index 097ae6f8b..8640c678f 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/jar/installer/ModrinthGetter.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/jar/installer/ModrinthGetter.java @@ -17,6 +17,7 @@ public class ModrinthGetter { public static final String projectID = "distanthorizons"; public static boolean initted = false; public static ArrayList projectRelease; + public static Map idToJson = new HashMap<>(); public static List releaseID = new ArrayList<>(); // This list contains the release ID's public static List mcVersions = new ArrayList<>(); // List of available Minecraft versions in the mod @@ -44,6 +45,7 @@ public class ModrinthGetter { String workingID = currentRelease.get("id").toString(); releaseID.add(workingID); + idToJson.put(workingID, currentRelease); releaseNames.put(workingID, currentRelease.get("name").toString().replaceAll(" - 1\\..*", "")); changeLogs.put(workingID, currentRelease.get("changelog").toString()); try { @@ -88,11 +90,9 @@ public class ModrinthGetter { return downloadUrl.get(mcVerToReleaseID.get(mcVer).get(0)); } public static String getLatestShaForVersion(String mcVer) { - return ((Config) - ((ArrayList) projectRelease.get( - mcVersions.indexOf(mcVer) - ).get("files")).get(0)) - .get("hashes.sha1") - .toString(); + return (((ArrayList) idToJson.get( + mcVerToReleaseID.get(mcVer).get(0) + ).get("files")).get(0).get("hashes.sha1") + .toString()); } } From 260358be93fa34693e78bc1ea13100e8d56d0c30 Mon Sep 17 00:00:00 2001 From: coolGi Date: Sun, 6 Aug 2023 18:57:38 +0930 Subject: [PATCH 16/24] Added pop-up notification on update success --- .../seibel/distanthorizons/core/jar/updater/SelfUpdater.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/jar/updater/SelfUpdater.java b/core/src/main/java/com/seibel/distanthorizons/core/jar/updater/SelfUpdater.java index d08f3efa3..047ae3915 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/jar/updater/SelfUpdater.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/jar/updater/SelfUpdater.java @@ -10,6 +10,7 @@ import com.seibel.distanthorizons.core.logging.DhLoggerBuilder; import com.seibel.distanthorizons.core.wrapperInterfaces.IVersionConstants; import org.apache.logging.log4j.Logger; +import javax.swing.*; import java.io.File; import java.net.URL; import java.nio.file.Files; @@ -107,6 +108,10 @@ public class SelfUpdater { deleteOldOnClose = true; LOGGER.info(ModInfo.READABLE_NAME + " successfully updated. It will apply on game's relaunch"); + new Thread(() -> { + System.setProperty("java.awt.headless", "false"); // Required to make it work + JOptionPane.showMessageDialog(null, ModInfo.READABLE_NAME+ " updated, this will be applied on game restart.", ModInfo.READABLE_NAME, JOptionPane.INFORMATION_MESSAGE); + }).start(); return true; } catch (Exception e) { LOGGER.warn("Failed to update "+ModInfo.READABLE_NAME+" to version "+ModrinthGetter.getLatestNameForVersion(minecraftVersion)); From f8f6c9f87721586d9ce1b8dab9bdfa7465d19018 Mon Sep 17 00:00:00 2001 From: coolGi Date: Sun, 6 Aug 2023 18:59:39 +0930 Subject: [PATCH 17/24] Added a ui button option + debug menu option --- .../distanthorizons/core/config/Config.java | 11 +- .../gui/standaloneTests/TestConfigMain.java | 171 ------------------ .../core/config/types/ConfigCategory.java | 3 +- .../core/config/types/ConfigUIButton.java | 25 +++ .../core/config/types/ConfigUIComment.java | 2 +- .../assets/distanthorizons/lang/en_us.json | 2 + 6 files changed, 37 insertions(+), 177 deletions(-) delete mode 100644 core/src/main/java/com/seibel/distanthorizons/core/config/gui/standaloneTests/TestConfigMain.java create mode 100644 core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigUIButton.java diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java b/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java index 49b63638b..b6098c976 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java @@ -30,16 +30,14 @@ import com.seibel.distanthorizons.core.config.eventHandlers.RenderCacheConfigEve import com.seibel.distanthorizons.core.config.eventHandlers.UnsafeValuesConfigListener; import com.seibel.distanthorizons.core.config.eventHandlers.presets.ThreadPresetConfigEventHandler; import com.seibel.distanthorizons.core.config.eventHandlers.presets.RenderQualityPresetConfigEventHandler; -import com.seibel.distanthorizons.core.config.types.ConfigCategory; -import com.seibel.distanthorizons.core.config.types.ConfigEntry; -import com.seibel.distanthorizons.core.config.types.ConfigLinkedEntry; -import com.seibel.distanthorizons.core.config.types.ConfigUIComment; +import com.seibel.distanthorizons.core.config.types.*; import com.seibel.distanthorizons.core.config.types.enums.EConfigEntryAppearance; import com.seibel.distanthorizons.core.config.types.enums.EConfigEntryPerformance; import com.seibel.distanthorizons.core.logging.DhLoggerBuilder; import com.seibel.distanthorizons.coreapi.ModInfo; import org.apache.logging.log4j.Logger; +import javax.swing.*; import java.util.*; @@ -1142,6 +1140,11 @@ public class Config public static ConfigEntry> listTest = new ConfigEntry.Builder>() .set(new ArrayList(Arrays.asList("option 1", "option 2", "option 3"))) .build(); + + public static ConfigUIButton uiButtonTest = new ConfigUIButton(() -> { + System.setProperty("java.awt.headless", "false"); // Required to make it work + JOptionPane.showMessageDialog(null, "Button pressed!", "UITester dialog", JOptionPane.INFORMATION_MESSAGE); + }); public static ConfigCategory categoryTest = new ConfigCategory.Builder().set(CategoryTest.class).build(); diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/gui/standaloneTests/TestConfigMain.java b/core/src/main/java/com/seibel/distanthorizons/core/config/gui/standaloneTests/TestConfigMain.java deleted file mode 100644 index f7b893722..000000000 --- a/core/src/main/java/com/seibel/distanthorizons/core/config/gui/standaloneTests/TestConfigMain.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.seibel.distanthorizons.core.config.gui.standaloneTests; - -import com.seibel.distanthorizons.core.config.gui.AbstractScreen; -import com.seibel.distanthorizons.core.config.gui.OpenGLConfigScreen; -import com.seibel.distanthorizons.core.pos.Pos2D; -import org.lwjgl.*; -import org.lwjgl.glfw.*; -import org.lwjgl.opengl.*; -import org.lwjgl.system.*; - -import java.nio.*; - -import static org.lwjgl.glfw.Callbacks.*; -import static org.lwjgl.glfw.GLFW.*; -import static org.lwjgl.opengl.GL11.*; -import static org.lwjgl.system.MemoryStack.*; -import static org.lwjgl.system.MemoryUtil.*; - -/** - * This just allows for a quicker testing of the config screen without loading up the whole game - * - * @author coolGi - */ -public class TestConfigMain { - // The window handle - private long window; - public AbstractScreen abstractScreen; - - - public static void main(String[] args) { - new TestConfigMain().run(); - } - - - public void run() { - abstractScreen = new OpenGLConfigScreen(); - System.out.println("Hello LWJGL version " + Version.getVersion()); - -// ClientApi.INSTANCE.rendererStartupEvent(); - init(); - - Pos2D windowDim = getWindowDimentions(window); - abstractScreen.width = windowDim.x; - abstractScreen.height = windowDim.y; - abstractScreen.init(); - loop(); - // Code isnt moved until loop is done (and it is only done if window is closed) - -// ClientApi.INSTANCE.rendererShutdownEvent(); - // Free the window callbacks and destroy the window - glfwFreeCallbacks(window); - glfwDestroyWindow(window); - - // Terminate GLFW and free the error callback - glfwTerminate(); - glfwSetErrorCallback(null).free(); - } - - private void init() { - // Setup an error callback. The default implementation - // will print the error message in System.err. - GLFWErrorCallback.createPrint(System.err).set(); - - // Initialize GLFW. Most GLFW functions will not work before doing this. - if ( !glfwInit() ) - throw new IllegalStateException("Unable to initialize GLFW"); - - // Configure GLFW - glfwDefaultWindowHints(); // optional, the current window hints are already the default - glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation - glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // the window will be resizable - - // Create the window - window = glfwCreateWindow(640, 480, "DH Test config", NULL, NULL); - if ( window == NULL ) - throw new RuntimeException("Failed to create the GLFW window"); - - // Setup a key callback. It will be called every time a key is pressed, repeated or released. - // Is this really nessesery -// glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> { -// if ( key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE ) -// glfwSetWindowShouldClose(window, true); // We will detect this in the rendering loop -// }); - - // Get the thread stack and push a new frame - try ( MemoryStack stack = stackPush() ) { - IntBuffer pWidth = stack.mallocInt(1); // int* - IntBuffer pHeight = stack.mallocInt(1); // int* - - // Get the window size passed to glfwCreateWindow - glfwGetWindowSize(window, pWidth, pHeight); - - // Get the resolution of the primary monitor - GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); - - // Center the window - glfwSetWindowPos( - window, - (vidmode.width() - pWidth.get(0)) / 2, - (vidmode.height() - pHeight.get(0)) / 2 - ); - } // the stack frame is popped automatically - - // Make the OpenGL context current - glfwMakeContextCurrent(window); - // Enable v-sync - glfwSwapInterval(1); - - // Make the window visible - glfwShowWindow(window); - GL.createCapabilities(); - } - - private void loop() { - // This line is critical for LWJGL's interoperation with GLFW's - // OpenGL context, or any context that is managed externally. - // LWJGL detects the context that is current in the current thread, - // creates the GLCapabilities instance and makes the OpenGL - // bindings available for use. - GL.createCapabilities(); - - // Set the clear color (if not set it would just be black) -// glClearColor(1.0f, 0.0f, 0.0f, 0.0f); - - // Set this so we can use it for the delta time - lastLoopTime = getTime(); - - // Run the rendering loop until the user has attempted to close - // the window or has pressed the ESCAPE key. - // (only works if glfwPollEvents() is called) - while ( !glfwWindowShouldClose(window) ) { - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer (will cause a ghosting effect if not called) - - // Poll for window events. (this allows the window to be closed) - glfwPollEvents(); - - Pos2D windowDim = getWindowDimentions(window); - abstractScreen.width = windowDim.x; - abstractScreen.height = windowDim.y; - - abstractScreen.render(getDelta()); - - - glfwSwapBuffers(window); // swap the color buffers - } - abstractScreen.onClose(); - } - - - - public Pos2D getWindowDimentions(long window) { - IntBuffer w = BufferUtils.createIntBuffer(1); - IntBuffer h = BufferUtils.createIntBuffer(1); - glfwGetWindowSize(window, w, h); - return new Pos2D(w.get(0), h.get(0)); - } - - - private double lastLoopTime; - private float timeCount; - public double getTime() { - return glfwGetTime(); - } - public float getDelta() { - double time = getTime(); - float delta = (float) (time - lastLoopTime); - lastLoopTime = time; - timeCount += delta; - return delta; - } -} diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigCategory.java b/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigCategory.java index cb282fc37..5197590f8 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigCategory.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigCategory.java @@ -3,12 +3,13 @@ package com.seibel.distanthorizons.core.config.types; import com.seibel.distanthorizons.core.config.types.enums.EConfigEntryAppearance; /** - * Adds a categoty to the config + * Adds a category to the config * See our config file for more information on how to use it * * @author coolGi */ public class ConfigCategory extends AbstractConfigType { + /** This should not be set by anything other than the config system itself */ public String destination; // Where the category goes to private ConfigCategory(EConfigEntryAppearance appearance, Class value, String destination) { diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigUIButton.java b/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigUIButton.java new file mode 100644 index 000000000..07f56fd77 --- /dev/null +++ b/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigUIButton.java @@ -0,0 +1,25 @@ +package com.seibel.distanthorizons.core.config.types; + +import com.seibel.distanthorizons.core.config.types.enums.EConfigEntryAppearance; + +public class ConfigUIButton extends AbstractConfigType { + public ConfigUIButton(Runnable runnable) { + super(EConfigEntryAppearance.ONLY_IN_GUI, runnable); + } + + public void runAction() { + new Thread(this.value).start(); + } + + public static class Builder extends AbstractConfigType.Builder { + /** Appearance shouldn't be changed */ + @Override + public Builder setAppearance(EConfigEntryAppearance newAppearance) { + return this; + } + + public ConfigUIButton build() { + return new ConfigUIButton(this.tmpValue); + } + } +} diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigUIComment.java b/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigUIComment.java index 75f8e075b..c0baf1e1d 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigUIComment.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/config/types/ConfigUIComment.java @@ -7,7 +7,7 @@ import com.seibel.distanthorizons.core.config.types.enums.EConfigEntryAppearance * * @author coolGi */ -public class ConfigUIComment extends AbstractConfigType{ +public class ConfigUIComment extends AbstractConfigType { public ConfigUIComment() { super(EConfigEntryAppearance.ONLY_IN_GUI, ""); } diff --git a/core/src/main/resources/assets/distanthorizons/lang/en_us.json b/core/src/main/resources/assets/distanthorizons/lang/en_us.json index 2120be320..c33fdeb45 100644 --- a/core/src/main/resources/assets/distanthorizons/lang/en_us.json +++ b/core/src/main/resources/assets/distanthorizons/lang/en_us.json @@ -460,6 +460,8 @@ "Float test", "distanthorizons.config.client.advanced.debugging.exampleConfigScreen.stringTest": "String test", + "distanthorizons.config.client.advanced.debugging.exampleConfigScreen.uiButtonTest": + "UI Button test", "distanthorizons.config.client.advanced.debugging.exampleConfigScreen.listTest": "List (ArrayList) test", "distanthorizons.config.client.advanced.debugging.exampleConfigScreen.mapTest": From 4de8812861cc08904693cf73150ed114576397ba Mon Sep 17 00:00:00 2001 From: James Seibel Date: Sun, 6 Aug 2023 17:39:34 -0500 Subject: [PATCH 18/24] update the seamless overdraw config to state it only works on fabric --- .../java/com/seibel/distanthorizons/core/config/Config.java | 5 +++-- .../main/resources/assets/distanthorizons/lang/en_us.json | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java b/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java index b6098c976..11a65cc44 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java @@ -511,9 +511,9 @@ public class Config + "Distant Horizons' and Minecraft's near/far clip planes, \n" + "reducing overdraw. \n" + "\n" - + "Only tested in Minecraft 1.18.2.\n" + + "Only functional on Fabric.\n" + "Works best with an overdraw prevention setting of "+EOverdrawPrevention.MEDIUM+" or higher \n" - + " nd cave culling disabled. \n" + + " and cave culling is disabled. \n" + "") .setPerformance(EConfigEntryPerformance.NONE) .build(); @@ -1129,6 +1129,7 @@ public class Config .set(42069L) .build(); + // doesn't show up in the UI right now public static ConfigEntry floatTest = new ConfigEntry.Builder() .set(0.42069f) .build(); diff --git a/core/src/main/resources/assets/distanthorizons/lang/en_us.json b/core/src/main/resources/assets/distanthorizons/lang/en_us.json index c33fdeb45..106798640 100644 --- a/core/src/main/resources/assets/distanthorizons/lang/en_us.json +++ b/core/src/main/resources/assets/distanthorizons/lang/en_us.json @@ -237,7 +237,7 @@ "distanthorizons.config.client.advanced.graphics.advancedGraphics.seamlessOverdraw": "(Experimental) Seamless Overdraw", "distanthorizons.config.client.advanced.graphics.advancedGraphics.seamlessOverdraw.@tooltip": - "Buggy experimental option that will attempt to match up \nDistant Horizons' and Minecraft's near/far clip planes, \nreducing overdraw.", + "Buggy experimental option that will attempt to match up \nDistant Horizons' and Minecraft's near/far clip planes, \nreducing overdraw. \n\nNote: only works with Fabric.", "distanthorizons.config.client.advanced.graphics.advancedGraphics.brightnessMultiplier": "Brightness Multiplier", "distanthorizons.config.client.advanced.graphics.advancedGraphics.brightnessMultiplier.@tooltip": From df63dd1370a57eecb9157598e910c58e3bf1082b Mon Sep 17 00:00:00 2001 From: James Seibel Date: Sun, 6 Aug 2023 17:47:07 -0500 Subject: [PATCH 19/24] Add a FullDataMetaFile TODO comment --- .../distanthorizons/core/file/fullDatafile/FullDataMetaFile.java | 1 + 1 file changed, 1 insertion(+) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/file/fullDatafile/FullDataMetaFile.java b/core/src/main/java/com/seibel/distanthorizons/core/file/fullDatafile/FullDataMetaFile.java index 168d04a28..bf7b6f91a 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/file/fullDatafile/FullDataMetaFile.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/file/fullDatafile/FullDataMetaFile.java @@ -175,6 +175,7 @@ public class FullDataMetaFile extends AbstractMetaDataContainerFile implements I this.fullDataSourceLoader = AbstractFullDataSourceLoader.getLoader(this.baseMetaData.dataTypeId, this.baseMetaData.binaryDataFormatVersion); if (this.fullDataSourceLoader == null) { + // TODO add a hard coded dictionary of known ID name combos so we can easily see in the log if the ID is valid or if the data was corrupted/old throw new IOException("Invalid file: Data type loader not found: "+this.baseMetaData.dataTypeId+"(v"+this.baseMetaData.binaryDataFormatVersion +")"); } From 38a7a837e774cb37df8865afb3bc9cc04e588e32 Mon Sep 17 00:00:00 2001 From: James Seibel Date: Sun, 6 Aug 2023 19:18:31 -0500 Subject: [PATCH 20/24] Fix incorrect unloaded chunk lighting --- .../core/api/internal/ServerApi.java | 30 +++++++++++++++++++ .../chunk/IChunkWrapper.java | 29 ++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/api/internal/ServerApi.java b/core/src/main/java/com/seibel/distanthorizons/core/api/internal/ServerApi.java index 4a0379701..f8584c925 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/api/internal/ServerApi.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/api/internal/ServerApi.java @@ -21,6 +21,7 @@ package com.seibel.distanthorizons.core.api.internal; import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiLevelLoadEvent; import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiLevelUnloadEvent; +import com.seibel.distanthorizons.core.generation.DhLightingEngine; import com.seibel.distanthorizons.core.wrapperInterfaces.misc.IServerPlayerWrapper; import com.seibel.distanthorizons.coreapi.DependencyInjection.ApiEventInjector; import com.seibel.distanthorizons.core.level.IDhLevel; @@ -34,6 +35,9 @@ import com.seibel.distanthorizons.core.wrapperInterfaces.world.ILevelWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IServerLevelWrapper; import org.apache.logging.log4j.Logger; +import java.util.LinkedList; +import java.util.List; + /** * This holds the methods that should be called by the host mod loader (Fabric, * Forge, etc.). Specifically server events. @@ -153,6 +157,32 @@ public class ServerApi IDhLevel dhLevel = SharedApi.getAbstractDhWorld().getLevel(level); if (dhLevel != null) { + + // Save or populate the chunk wrapper's lighting + // this is done so we don't have to worry about MC unloading the lighting data for this chunk + if (chunk.isLightCorrect()) + { + try + { + chunk.bakeDhLightingUsingMcLightingEngine(); + chunk.setUseDhLighting(true); + } + catch (IllegalStateException e) + { + LOGGER.warn(e.getMessage(), e); + } + } + else + { + // generate the chunk's lighting, ignoring neighbors. + // not a perfect solution, but should prevent chunks from having completely broken lighting + List nearbyChunkList = new LinkedList<>(); + nearbyChunkList.add(chunk); + DhLightingEngine.INSTANCE.lightChunks(chunk, nearbyChunkList, level.hasSkyLight() ? 15 : 0); + chunk.setUseDhLighting(true); + } + + dhLevel.updateChunkAsync(chunk); } } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/wrapperInterfaces/chunk/IChunkWrapper.java b/core/src/main/java/com/seibel/distanthorizons/core/wrapperInterfaces/chunk/IChunkWrapper.java index f699a174f..c48299c66 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/wrapperInterfaces/chunk/IChunkWrapper.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/wrapperInterfaces/chunk/IChunkWrapper.java @@ -53,6 +53,7 @@ public interface IChunkWrapper extends IBindable long getLongChunkPos(); void setIsDhLightCorrect(boolean isDhLightCorrect); + void setUseDhLighting(boolean useDhLighting); boolean isLightCorrect(); @@ -65,6 +66,34 @@ public interface IChunkWrapper extends IBindable int getBlockLight(int relX, int relY, int relZ); int getSkyLight(int relX, int relY, int relZ); + /** + * Populates DH's saved lighting using MC's lighting engine. + * This is generally done in cases where MC's lighting is correct now, but may not be later (like when a chunk is unloading). + * + * @throws IllegalStateException if the chunk's lighting isn't valid. This is done to prevent accidentally baking broken lighting. + */ + default void bakeDhLightingUsingMcLightingEngine() throws IllegalStateException + { + if (!this.isLightCorrect()) + { + throw new IllegalStateException("Unable to bake lighting for for chunk ["+this.getChunkPos()+"], Minecraft lighting not valid."); + } + + // get the lighting for every relative block pos + for (int relX = 0; relX < LodUtil.CHUNK_WIDTH; relX++) + { + for (int relZ = 0; relZ < LodUtil.CHUNK_WIDTH; relZ++) + { + for (int y = this.getMinBuildHeight(); y < this.getMaxBuildHeight(); y++) + { + this.setDhSkyLight(relX, y, relZ, this.getSkyLight(relX, y, relZ)); + this.setDhBlockLight(relX, y, relZ, this.getBlockLight(relX, y, relZ)); + } + } + } + } + + List getBlockLightPosList(); From 2930a899d8f299c02e4265f3dce1e6b524f00a55 Mon Sep 17 00:00:00 2001 From: James Seibel Date: Sun, 6 Aug 2023 19:21:46 -0500 Subject: [PATCH 21/24] Remove IMinecraftRenderWrapper.tryDisableVanillaFog() They are now handled via mixins --- .../distanthorizons/core/render/renderer/LodRenderer.java | 2 -- .../wrapperInterfaces/minecraft/IMinecraftRenderWrapper.java | 3 --- 2 files changed, 5 deletions(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderer.java b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderer.java index f622276af..02e84a119 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderer.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/render/renderer/LodRenderer.java @@ -161,8 +161,6 @@ public class LodRenderer drawSaveGLState.end("drawSaveGLState"); GLProxy glProxy = GLProxy.getInstance(); - if (Config.Client.Advanced.Graphics.Fog.disableVanillaFog.get()) - MC_RENDER.tryDisableVanillaFog(); //===================// // draw params setup // diff --git a/core/src/main/java/com/seibel/distanthorizons/core/wrapperInterfaces/minecraft/IMinecraftRenderWrapper.java b/core/src/main/java/com/seibel/distanthorizons/core/wrapperInterfaces/minecraft/IMinecraftRenderWrapper.java index d928cf8e7..f4e1c2a93 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/wrapperInterfaces/minecraft/IMinecraftRenderWrapper.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/wrapperInterfaces/minecraft/IMinecraftRenderWrapper.java @@ -134,8 +134,5 @@ public interface IMinecraftRenderWrapper extends IBindable ILightMapWrapper getLightmapWrapper(); - // Try and disable vanilla fog. Return true if successful, or false if not able to. - boolean tryDisableVanillaFog(); - } From 9f9c542a6c8b53494879fce9979e7ddae1953d16 Mon Sep 17 00:00:00 2001 From: coolGi Date: Mon, 7 Aug 2023 21:10:45 +0930 Subject: [PATCH 22/24] DH Jar now knows git version that it was built from --- .../distanthorizons/core/jar/ModGitInfo.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 core/src/main/java/com/seibel/distanthorizons/core/jar/ModGitInfo.java diff --git a/core/src/main/java/com/seibel/distanthorizons/core/jar/ModGitInfo.java b/core/src/main/java/com/seibel/distanthorizons/core/jar/ModGitInfo.java new file mode 100644 index 000000000..fabf0eb32 --- /dev/null +++ b/core/src/main/java/com/seibel/distanthorizons/core/jar/ModGitInfo.java @@ -0,0 +1,29 @@ +package com.seibel.distanthorizons.core.jar; + +import com.electronwill.nightconfig.core.Config; +import com.electronwill.nightconfig.core.io.ParsingMode; +import com.electronwill.nightconfig.json.JsonFormat; + +/** + * Get info on the git for the mod
+ * Warning: Gets generated on runtime + * + * @author coolGi + */ +public final class ModGitInfo { + static { + // Warning: Atm, this file is in the common subproject as the processResources task in gradle doesnt work for core + String s = JarUtils.convertInputStreamToString(JarUtils.accessFile("build_info.json")); + + Config jsonObject = Config.inMemory(); + JsonFormat.minimalInstance().createParser().parse(s, jsonObject, ParsingMode.REPLACE); + + Git_Main_Commit = jsonObject.get("git_main_commit"); + Git_Core_Commit = jsonObject.get("git_core_commit"); + Git_Main_Branch = jsonObject.get("git_main_branch"); + } + + public static final String Git_Main_Commit; + public static final String Git_Core_Commit; + public static final String Git_Main_Branch; +} From fc54e0f8939bc46cd27b43c7d3389450d0a35bbd Mon Sep 17 00:00:00 2001 From: coolGi Date: Mon, 7 Aug 2023 21:54:41 +0930 Subject: [PATCH 23/24] Fixed crashing with forge-config-api-port-fabric --- .../distanthorizons/core/config/Config.java | 8 ++++++-- .../core/config/file/ConfigFileHandling.java | 10 ++++++---- .../core/config/file/ConfigTypeConverters.java | 16 ++++++++++++---- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java b/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java index 11a65cc44..1ab41cbe1 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java @@ -1100,6 +1100,7 @@ public class Config .build(); /** This class is used to debug the different features of the config GUI */ + // FIXME: WARNING: Some of the options in this class dont get show n in the default UI public static class ExampleConfigScreen { // Defined in the lang, just a note about this screen @@ -1128,8 +1129,7 @@ public class Config public static ConfigEntry longTest = new ConfigEntry.Builder() .set(42069L) .build(); - - // doesn't show up in the UI right now + public static ConfigEntry floatTest = new ConfigEntry.Builder() .set(0.42069f) .build(); @@ -1142,6 +1142,10 @@ public class Config .set(new ArrayList(Arrays.asList("option 1", "option 2", "option 3"))) .build(); + public static ConfigEntry> mapTest = new ConfigEntry.Builder>() + .set(new HashMap()) + .build(); + public static ConfigUIButton uiButtonTest = new ConfigUIButton(() -> { System.setProperty("java.awt.headless", "false"); // Required to make it work JOptionPane.showMessageDialog(null, "Button pressed!", "UITester dialog", JOptionPane.INFORMATION_MESSAGE); diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/file/ConfigFileHandling.java b/core/src/main/java/com/seibel/distanthorizons/core/config/file/ConfigFileHandling.java index 83910c4ee..e8ef1fef5 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/config/file/ConfigFileHandling.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/config/file/ConfigFileHandling.java @@ -115,8 +115,9 @@ public class ConfigFileHandling { if (entry.getTrueValue() == null) throw new IllegalArgumentException("Entry ["+ entry.getNameWCategory() +"] is null, this may be a problem with ["+ configBase.modName +"]. Please contact the authors"); - if (ConfigTypeConverters.convertObjects.containsKey(entry.getType())) { - workConfig.set(entry.getNameWCategory(), ConfigTypeConverters.convertToString(entry.getType(), entry.getTrueValue())); + Class originalClass = ConfigTypeConverters.isClassConvertable(entry.getType()); + if (originalClass != null) { + workConfig.set(entry.getNameWCategory(), ConfigTypeConverters.convertToString(originalClass, entry.getTrueValue())); return; } workConfig.set(entry.getNameWCategory(), entry.getTrueValue()); @@ -141,8 +142,9 @@ public class ConfigFileHandling { entry.setWithoutSaving((T) ( workConfig.getEnum(entry.getNameWCategory(), (Class) entry.getType()))); return; } - if (ConfigTypeConverters.convertObjects.containsKey(entry.getType())) { - entry.setWithoutSaving((T) ConfigTypeConverters.convertFromString(entry.getType(), workConfig.get(entry.getNameWCategory()))); + Class originalClass = ConfigTypeConverters.isClassConvertable(entry.getType()); + if (originalClass != null) { + entry.setWithoutSaving((T) ConfigTypeConverters.convertFromString(originalClass, workConfig.get(entry.getNameWCategory()))); return; } diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/file/ConfigTypeConverters.java b/core/src/main/java/com/seibel/distanthorizons/core/config/file/ConfigTypeConverters.java index b2da5f8a7..0ac53df7b 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/config/file/ConfigTypeConverters.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/config/file/ConfigTypeConverters.java @@ -15,17 +15,25 @@ import java.util.Map; */ public class ConfigTypeConverters { // Once you've made a converter add it to here where the first value is the type you want to convert and the 2nd value is the converter - public static final Map convertObjects = new HashMap() {{ + public static final Map, ConverterBase> convertObjects = new HashMap, ConverterBase>() {{ put(Short.class, new ShortConverter()); put(Long.class, new LongConverter()); put(Float.class, new FloatConverter()); put(Byte.class, new ByteConverter()); put(Map.class, new MapConverter()); - put(HashMap.class, new MapConverter()); }}; - public static String convertToString(Class clazz, Object value) { + public static Class isClassConvertable(Class clazz) { + for (int i = 0; i < convertObjects.size(); i++) { + Class selectedClass = (Class) convertObjects.keySet().toArray()[i]; + if (selectedClass.isAssignableFrom(clazz)) + return selectedClass; + } + return null; + } + + public static String convertToString(Class clazz, Object value) { try { return convertObjects.get(clazz).convertToString(value); } catch (Exception e) { @@ -33,7 +41,7 @@ public class ConfigTypeConverters { return null; } } - public static Object convertFromString(Class clazz, String value) { + public static Object convertFromString(Class clazz, String value) { try { return convertObjects.get(clazz).convertFromString(value); } catch (Exception e) { From dc88c46dc98c86cb9d499afc5493897ec328a36c Mon Sep 17 00:00:00 2001 From: coolGi Date: Mon, 7 Aug 2023 22:05:04 +0930 Subject: [PATCH 24/24] Added a warning if value doesn't have a way to display it --- .../main/java/com/seibel/distanthorizons/core/config/Config.java | 1 + 1 file changed, 1 insertion(+) diff --git a/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java b/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java index 1ab41cbe1..380b8a643 100644 --- a/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java +++ b/core/src/main/java/com/seibel/distanthorizons/core/config/Config.java @@ -1101,6 +1101,7 @@ public class Config /** This class is used to debug the different features of the config GUI */ // FIXME: WARNING: Some of the options in this class dont get show n in the default UI + // This will throw a warning when opened in the default ui to tell you about it not showing public static class ExampleConfigScreen { // Defined in the lang, just a note about this screen