Compare commits

..
Author SHA1 Message Date
Pistonight 65d9bf8f2f copy depth buffer from MC for HUD caching 2024-01-26 10:34:46 -08:00
Jason Mitchell 3ee82e7157 OpenGL Debugging
* Move GLDebug and gl capabilitiesinto angelica/glsm instead of Iris
* Wire up GLDebug.pushGroup && popGroup via mixins if lwjgl debug is enabled (useful for api trace)
2024-01-24 20:33:09 -08:00
Pistonight 3b61bb74a2 fix hud caching alpha handling and boss health 2024-01-24 07:59:54 -08:00
Jason Mitchell f378b6e7ba VBO related Tweaks (#227)
* Expose original translation for tesselator, so we can reset it after doing VBO stuff

other small VBO cleanup

* Properly manage the tessellator's state...
2024-01-23 07:54:30 -08:00
Jason Mitchellandmakamys aff05e1812 Add Reese's Sodium Options (#219)
* Add Reese's Sodium Options

Co-authored-by: makamys <[email protected]>
2024-01-21 15:54:03 -08:00
Jason Mitchell 806bcf2d6b Config updates (#225)
* Make in game config for Angelica work
* Backport https://github.com/embeddedt/embeddium/commit/7476bf9b13fcb9a302722b350ef4e6e7d2b8a8c8 to rename angelica-options.json
2024-01-21 13:47:45 -08:00
makamys 3755e2595f Fix campfire backport animations (#224)
* Mark animations of crossed squares

Fixes Angelica's equivalent of https://github.com/GTNewHorizons/Hodgepodge/issues/264
Fixes Campfire Backport campfire flames not animating (but the embers and the
mixed NEI flames are still broken)

* Add Campfire Backport compatibility to animation speedup

Fixes Angelica's equivalent of https://github.com/GTNewHorizons/Hodgepodge/issues/204
Fixes embers and NEI mixed flames not animating
2024-01-21 09:12:30 -08:00
makamys 0d79f5e193 Make NotFine's sky toggle more granular (#222)
Separated "Sky" toggle into "Sky", "Sun & Moon", and "Stars", like in OptiFine.
This also fixes NF's sky toggle turning off MCPF's skybox
2024-01-21 08:33:10 -08:00
Jason Mitchellandmakamys 9210cd3283 ArchaicFix compat (#220)
* ArchaicFix compat

Fixes https://github.com/GTNewHorizons/Angelica/issues/216

* Update src/main/java/com/gtnewhorizons/angelica/mixins/TargetedMod.java

Co-authored-by: makamys <[email protected]>

---------

Co-authored-by: makamys <[email protected]>
2024-01-20 17:19:57 -08:00
makamys 733ffff81f Redirect negative display list calls to VBOs globally (fixes Smart Moving) (#217)
* Redirect negative display list calls to VBOs globally

Fixes Smart Moving not rendering player models

* Remove now redundant glCallList redirects

* Make VertexBuffer keep track of its own draw mode
2024-01-20 12:21:33 -08:00
Michael Zhao 32e2efc1e5 fix hud caching vignette and crosshair color issues (#212) 2024-01-20 10:17:48 -08:00
bombcar d9a688f1d8 fix runclient17 (#211) 2024-01-19 16:43:15 +00:00
Jason Mitchell ba66a0602b Update README.MD - No BetterFPS 2024-01-18 20:00:41 -08:00
Jason Mitchell d53a85e013 Remove silly early initial implementation and fix star VBO (#206)
* Remove silly early initial implementation and fix star VBO
2024-01-18 22:55:52 +00:00
mist475 5f6c418315 disable sodium weather quality redirect if dynamic surroundings is present as it overwrites the entire method (#200) 2024-01-16 09:29:22 -08:00
jss2a98aj 15569aadc7 Enable NotFine leaf modes when enableNotFineFeatures is true (#194)
* Use NotFine leaf modes if enableNotFineFeatures

* Sync NotFine langs
2024-01-15 15:23:44 -08:00
Jason Mitchell 0f97c09fda Render all Wavefront objects as VBO (#192)
* Tris actually seem to work w/ thaumcraft
2024-01-14 14:57:47 -08:00
Jason Mitchell fd43fbd9c9 Update README.MD 2024-01-14 10:12:04 -08:00
embeddedt 2b4ea9fd96 Don't activate item textures if there is no client world (#189) 2024-01-13 21:30:36 -08:00
tth05andJason Mitchell 1837dcec72 Replace fastutil dependency with GTNHLib (#187)
* Replace fastutil dependency with GTNHLib

* Add gtnhlib to mod dependencies

---------

Co-authored-by: Jason Mitchell <[email protected]>
2024-01-14 01:48:32 +00:00
Cyl18 84e1fa284b fix some of iris problems (#183) 2024-01-13 16:29:25 -08:00
Jason Mitchell c211d90faf Off thread safe blocks (#177)
* Whitelist carpentersblocks for off main thread rendering

* Add bounds checking to WorldSlice,

* Add preliminary `IThreadSafeISBRH` support

* Update TODO

* Adjust min y

* remove unnecessary try/catch

* * Keep track of what should be rendered on the main thread
* Update AngelicaBlockSafetyRegistry to handle vanilla blocks, and ISBHR's

* of -> set
2024-01-12 18:31:01 -08:00
Jason Mitchell 537eb06b66 Respect animation speedup config (#180) 2024-01-11 08:05:26 -08:00
Darren Eberly 93b03847df Only use BatchedFontRenderer when not in a display list compilation (#174) 2024-01-09 09:28:31 -05:00
Darren EberlyandJason Mitchell 85e44369bb Handle state changes for display lists correctly in GLSM (#168)
* Handle state changes in display lists correctly in GLSM

* Add some documentation so it's slightly more clear as to what's happening

---------

Co-authored-by: Jason Mitchell <[email protected]>
2024-01-08 21:48:15 +00:00
Raven Szewczyk fbc1b1b440 [ci skip] upgraded build system 2024-01-08 21:23:33 +00:00
embeddedt 97152a6ace Clear event phase before reusing object (#170) 2024-01-08 16:11:35 -05:00
makamysandJason Mitchell 3cde764d33 Update BS (#165)
* Update BS

Ran `updateBuildscript` and manually copied in the new `settings.gradle`

* Update build.gradle

---------

Co-authored-by: Jason Mitchell <[email protected]>
2024-01-08 03:25:38 +00:00
Jason Mitchell 45b20efc45 Change where the offset is reset (#159)
* Change where the offset is reset
* Debug log and rm dead code
2024-01-07 18:58:48 -08:00
106 changed files with 3258 additions and 795 deletions

No files matched your search

+7
View File
@@ -5,6 +5,10 @@
**Alpha Quality - Here there be Dragons**
# Required Dependencies
* [GTNHLib](https://github.com/GTNewHorizons/GTNHLib/releases) >= 0.2.1
# Known (temporary) Incompatibilities
* Forge Relocation - Currently non Thread Safe; safe if not in use
* ProjectRed Frames - Currently non Thread Safe; safe if not in use
@@ -16,6 +20,7 @@
# Permanent Incompatibilities
* Optifine [Disabled, won't fix]
* Fastcraft [Disable, won't fix]
* BetterFPS [Won't fix]
* LWJGL3ify 1.5.4 and below - Use the latest version available, 1.5.7+
* ArchaicFix 0.6.2 and below - Use 0.7.0 or above
* Hodgepodge 2.4.3 and below - [Use 2.4.4 or above](https://github.com/GTNewHorizons/Hodgepodge/releases)
@@ -38,6 +43,8 @@
* Sodium
* JellySquid & the CaffeineMC team, for making Sodium in the first place
* Embeddedt for [Embeddium](https://github.com/embeddedt/embeddium/tree/dc59ca357c25beefd6288f0d1d40b4cd8e670ab8) under the [LGPL 3.0](https://github.com/embeddedt/embeddium/blob/16.x/forge/LICENSE)
* Reese's Sodium Options
* FlashyReese for [Reese's Sodium Options](https://github.com/FlashyReese/reeses-sodium-options/tree/aa4ea67047cf53e54976e93c6bb1ab5ba16b142b) under the [MIT license](https://github.com/FlashyReese/reeses-sodium-options/blob/aa4ea67047cf53e54976e93c6bb1ab5ba16b142b/LICENSE.txt)
* Neodymium
* Makamys for [Neodymium](https://github.com/makamys/Neodymium) - Various Tessellator -> Quad functionality taken under the LGPL 3
* MCPatcherForge
+24 -5
View File
@@ -1,4 +1,4 @@
//version: 1704135167
//version: 1705357285
/*
DO NOT CHANGE THIS FILE!
Also, you may replace this file at any time if there is an update available.
@@ -53,7 +53,7 @@ plugins {
id 'com.diffplug.spotless' version '6.13.0' apply false // 6.13.0 is the last jvm8 supporting version
id 'com.modrinth.minotaur' version '2.+' apply false
id 'com.matthewprenger.cursegradle' version '1.4.0' apply false
id 'com.gtnewhorizons.retrofuturagradle' version '1.3.26'
id 'com.gtnewhorizons.retrofuturagradle' version '1.3.27'
}
print("You might want to check out './gradlew :faq' if your build fails.\n")
@@ -122,6 +122,7 @@ propertyDefaultIfUnset("modrinthProjectId", "")
propertyDefaultIfUnset("modrinthRelations", "")
propertyDefaultIfUnset("curseForgeProjectId", "")
propertyDefaultIfUnset("curseForgeRelations", "")
propertyDefaultIfUnset("versionPattern", "")
propertyDefaultIfUnset("minimizeShadowedDependencies", true)
propertyDefaultIfUnset("relocateShadowedDependencies", true)
// Deprecated properties (kept for backwards compat)
@@ -370,6 +371,7 @@ catch (Exception ignored) {
// Pulls version first from the VERSION env and then git tag
String identifiedVersion
String versionOverride = System.getenv("VERSION") ?: null
boolean checkVersion = false
try {
// Produce a version based on the tag, or for branches something like 0.2.2-configurable-maven-and-extras.38+43090270b6-dirty
if (versionOverride == null) {
@@ -388,6 +390,8 @@ try {
}
} else if (isDirty) {
identifiedVersion += "-${branchName}+${gitDetails.gitHash}-dirty"
} else {
checkVersion = true
}
} else {
identifiedVersion = versionOverride
@@ -409,6 +413,8 @@ ext {
if (identifiedVersion == versionOverride) {
out.style(Style.Failure).text('Override version to ').style(Style.Identifier).text(modVersion).style(Style.Failure).println('!\7')
} else if (checkVersion && versionPattern && !(identifiedVersion ==~ versionPattern)) {
throw new GradleException("Invalid version: '$identifiedVersion' does not match version pattern '$versionPattern'")
}
group = "com.github.GTNewHorizons"
@@ -428,18 +434,31 @@ minecraft {
for (f in replaceGradleTokenInFile.split(',')) {
tagReplacementFiles.add f
}
out.style(Style.Info).text('replaceGradleTokenInFile is deprecated! Consider using generateGradleTokenClass.').println()
}
if (gradleTokenModId) {
injectedTags.put gradleTokenModId, modId
if (replaceGradleTokenInFile) {
injectedTags.put gradleTokenModId, modId
} else {
out.style(Style.Failure).text('gradleTokenModId is deprecated! The field will no longer be generated.').println()
}
}
if (gradleTokenModName) {
injectedTags.put gradleTokenModName, modName
if (replaceGradleTokenInFile) {
injectedTags.put gradleTokenModName, modName
} else {
out.style(Style.Failure).text('gradleTokenModName is deprecated! The field will no longer be generated.').println()
}
}
if (gradleTokenVersion) {
injectedTags.put gradleTokenVersion, modVersion
}
if (gradleTokenGroupName) {
injectedTags.put gradleTokenGroupName, modGroup
if (replaceGradleTokenInFile) {
injectedTags.put gradleTokenGroupName, modGroup
} else {
out.style(Style.Failure).text('gradleTokenGroupName is deprecated! The field will no longer be generated.').println()
}
}
if (enableGenericInjection.toBoolean()) {
injectMissingGenerics.set(true)
+2 -1
View File
@@ -56,7 +56,7 @@ dependencies {
// Iris Shaders
compileOnly('org.jetbrains:annotations:24.0.1')
shadowImplementation("it.unimi.dsi:fastutil:8.2.1") // Apache 2.0
api("com.github.GTNewHorizons:GTNHLib:0.2.1:dev")
shadowImplementation("org.joml:joml:1.10.5") // MIT
shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0
implementation("io.github.douira:glsl-transformer:1.0.0")
@@ -85,6 +85,7 @@ dependencies {
compileOnly("com.github.GTNewHorizons:NotEnoughIds-Legacy:1.4.7:dev") // ASM Version
compileOnly("com.github.GTNewHorizons:Jabba:1.3.1:dev")
compileOnly(rfg.deobf("curse.maven:campfirebackport-387444:4611675"))
// HMMMMM
compileOnly(rfg.deobf("curse.maven:journeymap-32274:2367915"))
Binary file not shown.
+2 -1
View File
@@ -1,6 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+13 -9
View File
@@ -83,7 +83,8 @@ done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -130,10 +131,13 @@ location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
@@ -141,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
@@ -149,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -198,11 +202,11 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
+5 -6
View File
@@ -4,10 +4,9 @@ pluginManagement {
maven {
// RetroFuturaGradle
name "GTNH Maven"
url "http://jenkins.usrv.eu:8081/nexus/content/groups/public/"
allowInsecureProtocol = true
url "https://nexus.gtnewhorizons.com/repository/public/"
mavenContent {
includeGroup("com.gtnewhorizons.retrofuturagradle")
includeGroupByRegex("com\\.gtnewhorizons\\..+")
}
}
gradlePluginPortal()
@@ -17,12 +16,12 @@ pluginManagement {
}
plugins {
id 'com.diffplug.blowdryerSetup' version '1.6.0'
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.4.0' // Provides java toolchains
id 'com.diffplug.blowdryerSetup' version '1.7.1'
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.7.0' // Provides java toolchains
}
blowdryerSetup {
repoSubfolder 'gtnhShared'
github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.2.0')
github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.2.2')
//devLocal '.' // Use this when testing config updates locally
}
@@ -15,9 +15,10 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent;
name = "Angelica",
version = Tags.VERSION,
dependencies = " before:lwjgl3ify@[1.5.3,);" + " after:hodgepodge@[2.4.4,);" + " after:CodeChickenCore@[1.2.0,);"
+ " after:archaicfix@[0.7.0,);",
+ " after:archaicfix@[0.7.0,);" + " required-after:gtnhlib@[0.2.1,);",
acceptedMinecraftVersions = "[1.7.10]",
acceptableRemoteVersions = "*")
acceptableRemoteVersions = "*",
guiFactory = "com.gtnewhorizons.angelica.config.AngelicaGuiConfigFactory")
public class AngelicaMod {
@SidedProxy(clientSide = "com.gtnewhorizons.angelica.proxy.ClientProxy", serverSide = "com.gtnewhorizons.angelica.proxy.CommonProxy")
public static CommonProxy proxy;
@@ -0,0 +1,29 @@
package com.gtnewhorizons.angelica.client.gui;
import com.gtnewhorizons.angelica.compat.mojang.Element;
import net.minecraft.client.gui.GuiScreen;
import org.lwjgl.input.Mouse;
import java.util.List;
public abstract class ScrollableGuiScreen extends GuiScreen {
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
super.drawScreen(mouseX, mouseY, partialTicks);
handleMouseScroll(mouseX, mouseY, partialTicks);
}
public abstract List<? extends Element> children();
protected void handleMouseScroll(int mouseX, int mouseY, float partialTicks) {
for (; !this.mc.gameSettings.touchscreen && Mouse.next(); this.mc.currentScreen.handleMouseInput()) {
int dWheel = Mouse.getEventDWheel();
if (dWheel != 0) {
for(Element child : children()) {
child.mouseScrolled(mouseX, mouseY, dWheel);
}
}
}
}
}
@@ -9,6 +9,7 @@ import cpw.mods.fml.relauncher.ReflectionHelper;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import me.jellysquid.mods.sodium.client.render.pipeline.BlockRenderer;
import net.minecraft.client.renderer.Tessellator;
import org.joml.Vector3d;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
@@ -44,12 +45,19 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns
// Any offset we need to the Tesselator's offset!
private final BlockPos offset = new BlockPos();
private final Vector3d storedTranslation = new Vector3d();
private boolean translationStored = false;
public void setOffset(BlockPos pos) {
this.offset.set(pos);
}
public void resetOffset() {
this.offset.zero();
}
static {
Field rbs = ReflectionHelper.findField(Tessellator.class, "rawBufferSize");
final Field rbs = ReflectionHelper.findField(Tessellator.class, "rawBufferSize");
rbs.setAccessible(true);
try {
sRawBufferSize = MethodHandles.lookup().unreflectSetter(rbs);
@@ -82,11 +90,6 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns
FLAGS.hasColor = this.hasColor;
FLAGS.hasNormals = this.hasNormals;
// TODO: Support GL_TRIANGLES
if(this.drawMode != GL11.GL_QUADS) {
throw new IllegalStateException("Currently only supports GL_QUADS");
}
final int verticesPerPrimitive = this.drawMode == GL11.GL_QUADS ? 4 : 3;
@@ -106,12 +109,6 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns
return i;
}
@Override
public void reset() {
super.reset();
this.offset.zero();
}
@Override
public void discard() {
isDrawing = false;
@@ -144,6 +141,22 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns
return byteBuffer;
}
public void storeTranslation() {
if(translationStored) throw new IllegalStateException("Translation already stored!");
translationStored = true;
this.storedTranslation.set(xOffset, yOffset, zOffset);
}
public void restoreTranslation() {
if(!translationStored) throw new IllegalStateException("Translation not stored!");
xOffset = storedTranslation.x;
yOffset = storedTranslation.y;
zOffset = storedTranslation.z;
storedTranslation.zero();
translationStored = false;
}
public static int createBrightness(int sky, int block) {
return sky << 20 | block << 4;
}
@@ -232,4 +245,5 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns
}
}
}
}
@@ -80,6 +80,9 @@ public class BlockPos extends Vector3i {
return l;
}
public BlockPos set(long packedPos) {
return set(unpackLongX(packedPos), unpackLongY(packedPos), unpackLongZ(packedPos));
}
public static int unpackLongX(long packedPos) {
return (int)(packedPos << 64 - BIT_SHIFT_X - SIZE_BITS_X >> 64 - SIZE_BITS_X);
@@ -0,0 +1,5 @@
package com.gtnewhorizons.angelica.compat.mojang;
public interface Drawable {
default void render(int mouseX, int mouseY, float delta) {}
}
@@ -0,0 +1,29 @@
package com.gtnewhorizons.angelica.compat.mojang;
public interface Element {
default boolean mouseClicked(double mouseX, double mouseY, int button) {
return false;
}
default boolean mouseDragged(double mouseX, double mouseY, int button) {
return false;
}
default boolean mouseReleased(double mouseX, double mouseY, int button) {
return false;
}
default boolean mouseScrolled(double mouseX, double mouseY, double amount) {
return false;
}
default boolean keyTyped(char typedChar, int keyCode) { return false; }
default boolean isMouseOver(double mouseX, double mouseY) {
return false;
}
default boolean changeFocus(boolean lookForwards) {
return false;
}
}
@@ -0,0 +1,97 @@
package com.gtnewhorizons.angelica.compat.mojang;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.ListIterator;
import java.util.Optional;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
public interface ParentElement extends Element {
List<? extends Element> children();
default Optional<Element> hoveredElement(double mouseX, double mouseY) {
for(Element element : this.children()) {
if (element.isMouseOver(mouseX, mouseY)) {
return Optional.of(element);
}
}
return Optional.empty();
}
default boolean mouseClicked(double mouseX, double mouseY, int button) {
for(Element element : this.children()) {
if (element.mouseClicked(mouseX, mouseY, button)) {
this.setFocused(element);
if (button == 0) {
this.setDragging(true);
}
return true;
}
}
return false;
}
default boolean mouseReleased(double mouseX, double mouseY, int button) {
this.setDragging(false);
return this.hoveredElement(mouseX, mouseY).filter((element) -> element.mouseReleased(mouseX, mouseY, button)).isPresent();
}
default boolean mouseDragged(double mouseX, double mouseY, int button) {
return this.getFocused() != null && this.isDragging() && button == 0 && this.getFocused().mouseDragged(mouseX, mouseY, button);
}
boolean isDragging();
void setDragging(boolean dragging);
default boolean mouseScrolled(double mouseX, double mouseY, double amount) {
return this.hoveredElement(mouseX, mouseY).filter((element) -> element.mouseScrolled(mouseX, mouseY, amount)).isPresent();
}
default boolean keyTyped(char typedChar, int keyCode) {
return this.getFocused() != null && this.getFocused().keyTyped(typedChar, keyCode);
}
@Nullable
Element getFocused();
void setFocused(@Nullable Element focused);
default boolean changeFocus(boolean lookForwards) {
final Element element = this.getFocused();
if (element != null && element.changeFocus(lookForwards)) {
return true;
} else {
final List<? extends Element> list = this.children();
final int i = list.indexOf(element);
final int j;
if (element != null && i >= 0) {
j = i + (lookForwards ? 1 : 0);
} else if (lookForwards) {
j = 0;
} else {
j = list.size();
}
final ListIterator<? extends Element> listIterator = list.listIterator(j);
final BooleanSupplier booleanSupplier = lookForwards ? listIterator::hasNext : listIterator::hasPrevious;
final Supplier<? extends Element> supplier = lookForwards ? listIterator::next : listIterator::previous;
Element element2;
do {
if (!booleanSupplier.getAsBoolean()) {
this.setFocused(null);
return false;
}
element2 = supplier.get();
} while(!element2.changeFocus(lookForwards));
this.setFocused(element2);
return true;
}
}
}
@@ -11,14 +11,16 @@ public class VertexBuffer implements AutoCloseable {
private int id;
private int vertexCount;
private VertexFormat format;
private int drawMode;
public VertexBuffer() {
this.id = GL15.glGenBuffers();
}
public VertexBuffer(VertexFormat format) {
public VertexBuffer(VertexFormat format, int drawMode) {
this();
this.format = format;
this.drawMode = drawMode;
}
public void bind() {
@@ -39,7 +41,7 @@ public class VertexBuffer implements AutoCloseable {
public VertexBuffer upload(ByteBuffer buffer) {
if(format == null) throw new IllegalStateException("No format specified for VBO upload");
upload(buffer, buffer.capacity() / format.getVertexSize());
upload(buffer, buffer.remaining() / format.getVertexSize());
return this;
}
@@ -50,16 +52,16 @@ public class VertexBuffer implements AutoCloseable {
}
}
public void draw(FloatBuffer floatBuffer, int mode) {
public void draw(FloatBuffer floatBuffer) {
GL11.glPushMatrix();
GL11.glLoadIdentity();
GL11.glMultMatrix(floatBuffer);
draw(mode);
draw();
GL11.glPopMatrix();
}
public void draw(int mode) {
GL11.glDrawArrays(mode, 0, this.vertexCount);
public void draw() {
GL11.glDrawArrays(drawMode, 0, this.vertexCount);
}
public void setupState() {
@@ -72,12 +74,9 @@ public class VertexBuffer implements AutoCloseable {
format.clearBufferState();
unbind();
}
public void render(int mode) {
if(format == null) throw new IllegalStateException("No format specified for VBO render");
bind();
format.setupBufferState(0L);
draw(mode);
format.clearBufferState();
unbind();
public void render() {
setupState();
draw();
cleanupState();
}
}
@@ -112,7 +112,7 @@ public class Quad implements ModelQuadView {
}
private void read(int[] rawBuffer, int offset, float offsetX, float offsetY, float offsetZ, int drawMode, BlockRenderer.Flags flags) {
int vertices = drawMode == GL11.GL_TRIANGLES ? 3 : 4;
final int vertices = drawMode == GL11.GL_TRIANGLES ? 3 : 4;
for(int vi = 0; vi < vertices; vi++) {
int i = offset + vi * 8;
@@ -7,6 +7,10 @@ public class AngelicaConfig {
@Config.RequiresMcRestart
public static boolean enableSodium;
@Config.Comment("Enable Reese's Sodium Options")
@Config.DefaultBoolean(true)
public static boolean enableReesesSodiumOptions;
@Config.Comment("Enable Sodium fluid rendering")
@Config.DefaultBoolean(false)
@Config.RequiresMcRestart
@@ -4,6 +4,6 @@ import net.minecraft.client.gui.GuiScreen;
public class AngelicaGuiConfig extends SimpleGuiConfig {
public AngelicaGuiConfig(GuiScreen parent) throws ConfigException {
super(parent, AngelicaConfig.class, "archaicfix", "ArchaicFix");
super(parent, AngelicaConfig.class, "angelica", "Angelica");
}
}
@@ -0,0 +1,35 @@
package com.gtnewhorizons.angelica.config;
import net.minecraft.client.Minecraft;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ConfigMigrator {
public static Logger LOGGER = LogManager.getLogger("Angelica");
/**
* Tries to migrate the equivalent config file from Rubidium to the Angelica name if possible.
*/
public static Path handleConfigMigration(String fileName) {
final Path configDir = Minecraft.getMinecraft().mcDataDir.toPath().resolve("config");
final Path mainPath = configDir.resolve(fileName);
try {
if(Files.notExists(mainPath)) {
final String legacyName = fileName.replace("angelica", "rubidium");
final Path legacyPath = configDir.resolve(legacyName);
if(Files.exists(legacyPath)) {
Files.move(legacyPath, mainPath);
LOGGER.warn("Migrated {} config file to {}", legacyName, fileName);
}
}
} catch(IOException | RuntimeException e) {
LOGGER.error("Exception encountered while attempting config migration", e);
}
return mainPath;
}
}
@@ -3,11 +3,8 @@
* License terms: https://www.lwjgl.org/license
*/
package net.coderbot.iris.gl;
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.loading.AngelicaTweaker;
import net.coderbot.iris.Iris;
import org.lwjgl.opengl.AMDDebugOutput;
import org.lwjgl.opengl.AMDDebugOutputCallback;
import org.lwjgl.opengl.ARBDebugOutput;
@@ -21,6 +18,7 @@ import org.lwjgl.opengl.KHRDebugCallback;
import java.io.PrintStream;
import java.util.function.Consumer;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
import static org.lwjgl.opengl.ARBDebugOutput.glDebugMessageCallbackARB;
public final class GLDebug {
@@ -30,7 +28,7 @@ public final class GLDebug {
*/
public static int setupDebugMessageCallback() {
if (Thread.currentThread() != GLStateManager.getMainThread()) {
AngelicaTweaker.LOGGER.warn("setupDebugMessageCallback called from non-main thread!");
LOGGER.warn("setupDebugMessageCallback called from non-main thread!");
return 0;
}
return setupDebugMessageCallback(System.err);
@@ -64,7 +62,7 @@ public final class GLDebug {
return throwable;
}
private static void printTrace(PrintStream stream) {
public static void printTrace(PrintStream stream) {
trace(new Consumer<String>() {
boolean first = true;
@@ -84,8 +82,8 @@ public final class GLDebug {
* @return 0 for failure, 1 for success, 2 for restart required.
*/
public static int setupDebugMessageCallback(PrintStream stream) {
if (Iris.capabilities.OpenGL43 || Iris.capabilities.GL_KHR_debug) {
Iris.logger.info("[GL] Using OpenGL 4.3 for error logging.");
if (GLStateManager.capabilities.OpenGL43 || GLStateManager.capabilities.GL_KHR_debug) {
LOGGER.info("[GL] Using OpenGL 4.3 for error logging.");
KHRDebugCallback proc = new KHRDebugCallback((source, type, id, severity, message) -> {
stream.println("[LWJGL] OpenGL debug message");
printDetail(stream, "ID", String.format("0x%X", id));
@@ -102,13 +100,13 @@ public final class GLDebug {
GL43.glDebugMessageCallback(proc);
if ((GL11.glGetInteger(GL30.GL_CONTEXT_FLAGS) & GL43.GL_CONTEXT_FLAG_DEBUG_BIT) == 0) {
Iris.logger.warn("[GL] Warning: A non-debug context may not produce any debug output.");
LOGGER.warn("[GL] Warning: A non-debug context may not produce any debug output.");
GL11.glEnable(GL43.GL_DEBUG_OUTPUT);
return 2;
}
return 1;
} else if (Iris.capabilities.GL_ARB_debug_output) {
Iris.logger.info("[GL] Using ARB_debug_output for error logging.");
} else if (GLStateManager.capabilities.GL_ARB_debug_output) {
LOGGER.info("[GL] Using ARB_debug_output for error logging.");
ARBDebugOutputCallback proc = new ARBDebugOutputCallback((source, type, id, severity, message) -> {
stream.println("[LWJGL] ARB_debug_output message");
printDetail(stream, "ID", String.format("0x%X", id));
@@ -124,8 +122,8 @@ public final class GLDebug {
ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_NOTIFICATION, null, false);
ARBDebugOutput.glDebugMessageCallbackARB(proc);
return 1;
} else if (Iris.capabilities.GL_AMD_debug_output) {
Iris.logger.info("[GL] Using AMD_debug_output for error logging.");
} else if (GLStateManager.capabilities.GL_AMD_debug_output) {
LOGGER.info("[GL] Using AMD_debug_output for error logging.");
AMDDebugOutputCallback proc = new AMDDebugOutputCallback((id, category, severity, message) -> {
stream.println("[LWJGL] AMD_debug_output message");
printDetail(stream, "ID", String.format("0x%X", id));
@@ -141,29 +139,29 @@ public final class GLDebug {
AMDDebugOutput.glDebugMessageCallbackAMD(proc);
return 1;
} else {
Iris.logger.info("[GL] No debug output implementation is available, cannot return debug info.");
LOGGER.info("[GL] No debug output implementation is available, cannot return debug info.");
return 0;
}
}
public static int disableDebugMessages() {
if (Iris.capabilities.OpenGL43) {
if (GLStateManager.capabilities.OpenGL43) {
GL43.glDebugMessageCallback(null);
return 1;
} else if (Iris.capabilities.GL_KHR_debug) {
} else if (GLStateManager.capabilities.GL_KHR_debug) {
KHRDebug.glDebugMessageCallback(null);
if (Iris.capabilities.OpenGL30 && (GL11.glGetInteger(GL30.GL_CONTEXT_FLAGS) & 2) == 0) {
if (GLStateManager.capabilities.OpenGL30 && (GL11.glGetInteger(GL30.GL_CONTEXT_FLAGS) & 2) == 0) {
GL11.glDisable(GL43.GL_DEBUG_OUTPUT);
}
return 1;
} else if (Iris.capabilities.GL_ARB_debug_output) {
} else if (GLStateManager.capabilities.GL_ARB_debug_output) {
glDebugMessageCallbackARB(null);
return 1;
} else if (Iris.capabilities.GL_AMD_debug_output) {
} else if (GLStateManager.capabilities.GL_AMD_debug_output) {
AMDDebugOutput.glDebugMessageCallbackAMD(null);
return 1;
} else {
Iris.logger.info("[GL] No debug output implementation is available, cannot disable debug info.");
LOGGER.info("[GL] No debug output implementation is available, cannot disable debug info.");
return 0;
}
}
@@ -273,14 +271,17 @@ public final class GLDebug {
private static DebugState debugState;
private static interface DebugState {
private interface DebugState {
void nameObject(int id, int object, String name);
void pushGroup(int id, String name);
void pushGroup(String name);
void popGroup();
void debugMessage(String name);
}
private static class KHRDebugState implements DebugState {
private boolean hasGroup;
private static final int ID = 0;
private int depth = 0;
private static final int maxDepth = GL11.glGetInteger(KHRDebug.GL_MAX_DEBUG_GROUP_STACK_DEPTH);
@Override
public void nameObject(int id, int object, String name) {
@@ -288,19 +289,28 @@ public final class GLDebug {
}
@Override
public void pushGroup(int id, String name) {
KHRDebug.glPushDebugGroup(KHRDebug.GL_DEBUG_SOURCE_APPLICATION, id, name);
hasGroup = true;
public void pushGroup(String name) {
depth++;
if (depth > maxDepth) {
throw new RuntimeException("Stack overflow");
}
KHRDebug.glPushDebugGroup(KHRDebug.GL_DEBUG_SOURCE_APPLICATION, ID, name);
}
@Override
public void popGroup() {
if (hasGroup) {
KHRDebug.glPopDebugGroup();
hasGroup = false;
}
depth--;
if (depth < 0) {
throw new RuntimeException("Stack underflow");
}
KHRDebug.glPopDebugGroup();
}
}
@Override
public void debugMessage(String message) {
KHRDebug.glDebugMessageInsert(KHRDebug.GL_DEBUG_SOURCE_APPLICATION, KHRDebug.GL_DEBUG_TYPE_MARKER, ID, KHRDebug.GL_DEBUG_SEVERITY_NOTIFICATION, message);
}
}
private static class UnsupportedDebugState implements DebugState {
@Override
@@ -308,16 +318,21 @@ public final class GLDebug {
}
@Override
public void pushGroup(int id, String name) {
public void pushGroup(String name) {
}
@Override
public void popGroup() {
}
}
public static void initRenderer() {
if (Iris.capabilities.GL_KHR_debug || Iris.capabilities.OpenGL43) {
@Override
public void debugMessage(String name) {
}
}
public static void initDebugState() {
if (GLStateManager.capabilities.GL_KHR_debug || GLStateManager.capabilities.OpenGL43) {
debugState = new KHRDebugState();
} else {
debugState = new UnsupportedDebugState();
@@ -325,6 +340,23 @@ public final class GLDebug {
}
public static void nameObject(int id, int object, String name) {
debugState.nameObject(id, object, name);
if(debugState != null && Thread.currentThread() == GLStateManager.getMainThread()) {
debugState.nameObject(id, object, name);
}
}
public static void pushGroup(String group) {
if(debugState != null && Thread.currentThread() == GLStateManager.getMainThread()) {
debugState.pushGroup(group);
}
}
public static void popGroup() {
if(debugState != null && Thread.currentThread() == GLStateManager.getMainThread()) {
debugState.popGroup();
}
}
public static void debugMessage(String message) {
if(debugState != null && Thread.currentThread() == GLStateManager.getMainThread()) {
debugState.debugMessage(message);
}
}
}
@@ -45,16 +45,19 @@ import org.joml.Vector3f;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.ARBMultitexture;
import org.lwjgl.opengl.ContextCapabilities;
import org.lwjgl.opengl.Drawable;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GLContext;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.AbstractMap;
import java.util.Map;
import java.util.Set;
@@ -62,6 +65,8 @@ import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
@SuppressWarnings("unused") // Used in ASM
public class GLStateManager {
public static ContextCapabilities capabilities;
public static final boolean BYPASS_CACHE = Boolean.parseBoolean(System.getProperty("angelica.disableGlCache", "false"));
public static final int MAX_ATTRIB_STACK_DEPTH = GL11.glGetInteger(GL11.GL_MAX_ATTRIB_STACK_DEPTH);
public static final int MAX_MODELVIEW_STACK_DEPTH = GL11.glGetInteger(GL11.GL_MAX_MODELVIEW_STACK_DEPTH);
@@ -78,6 +83,7 @@ public class GLStateManager {
@Getter protected static final TextureUnitArray textures = new TextureUnitArray();
@Getter protected static final BlendStateStack blendState = new BlendStateStack();
@Getter protected static final BooleanStateStack blendMode = new BooleanStateStack(GL11.GL_BLEND);
@Getter protected static final BooleanStateStack scissorTest = new BooleanStateStack(GL11.GL_SCISSOR_TEST);
@Getter protected static final DepthStateStack depthState = new DepthStateStack();
@Getter protected static final BooleanStateStack depthTest = new BooleanStateStack(GL11.GL_DEPTH_TEST);
@@ -122,9 +128,9 @@ public class GLStateManager {
private static final Map<IStateStack<?>, ISettableState<?>> glListStates = new Object2ObjectArrayMap<>();
private static final Int2ObjectMap<Set<Map.Entry<IStateStack<?>, ISettableState<?>>>> glListChanges = new Int2ObjectOpenHashMap<>();
private static boolean hudCaching$blendEnabled;
public static void init() {
capabilities = GLContext.getCapabilities();
if (AngelicaConfig.enableIris) {
StateUpdateNotifiers.blendFuncNotifier = listener -> blendFuncListener = listener;
StateUpdateNotifiers.fogToggleNotifier = listener -> fogToggleListener = listener;
@@ -133,8 +139,21 @@ public class GLStateManager {
StateUpdateNotifiers.fogEndNotifier = listener -> fogEndListener = listener;
StateUpdateNotifiers.fogDensityNotifier = listener -> fogDensityListener = listener;
}
if(BYPASS_CACHE) {
LOGGER.info("GLStateManager cache bypassed");
}
if(AngelicaMod.lwjglDebug) {
LOGGER.info("Enabling additional LWJGL debug output");
GLDebug.setupDebugMessageCallback();
GLDebug.initDebugState();
GLDebug.debugMessage("Angelica Debug Annotator Initialized");
}
}
public static void assertMainThread() {
if (Thread.currentThread() != CurrentThread && !runningSplash) {
LOGGER.info("Call from not the Current Thread! - " + Thread.currentThread().getName() + " Current thread: " + CurrentThread.getName());
@@ -152,6 +171,7 @@ public class GLStateManager {
case GL12.GL_RESCALE_NORMAL -> enableRescaleNormal();
case GL11.GL_TEXTURE_2D -> enableTexture();
case GL11.GL_FOG -> enableFog();
case GL11.GL_SCISSOR_TEST -> enableScissorTest();
default -> GL11.glEnable(cap);
}
}
@@ -166,6 +186,7 @@ public class GLStateManager {
case GL12.GL_RESCALE_NORMAL -> disableRescaleNormal();
case GL11.GL_TEXTURE_2D -> disableTexture();
case GL11.GL_FOG -> disableFog();
case GL11.GL_SCISSOR_TEST -> disableScissorTest();
default -> GL11.glDisable(cap);
}
}
@@ -197,7 +218,6 @@ public class GLStateManager {
return;
}
}
hudCaching$blendEnabled = true;
blendMode.enable();
}
@@ -208,10 +228,17 @@ public class GLStateManager {
return;
}
}
hudCaching$blendEnabled = false;
blendMode.disable();
}
public static void enableScissorTest() {
scissorTest.enable();
}
public static void disableScissorTest() {
scissorTest.disable();
}
public static void glBlendFunc(int srcFactor, int dstFactor) {
if (AngelicaConfig.enableIris) {
if (BlendModeStorage.isBlendLocked()) {
@@ -284,36 +311,24 @@ public class GLStateManager {
}
public static void glColor4f(float red, float green, float blue, float alpha) {
if (!hudCaching$blendEnabled && HUDCaching.renderingCacheOverride && alpha < 1f) {
alpha = 1f;
}
if (changeColor(red, green, blue, alpha)) {
GL11.glColor4f(red, green, blue, alpha);
}
}
public static void glColor4d(double red, double green, double blue, double alpha) {
if (!hudCaching$blendEnabled && HUDCaching.renderingCacheOverride && alpha < 1d) {
alpha = 1d;
}
if (changeColor((float) red, (float) green, (float) blue, (float) alpha)) {
GL11.glColor4d(red, green, blue, alpha);
}
}
public static void glColor4b(byte red, byte green, byte blue, byte alpha) {
if (!hudCaching$blendEnabled && HUDCaching.renderingCacheOverride && alpha < Byte.MAX_VALUE) {
alpha = Byte.MAX_VALUE;
}
if (changeColor(b2f(red), b2f(green), b2f(blue), b2f(alpha))) {
GL11.glColor4b(red, green, blue, alpha);
}
}
public static void glColor4ub(byte red, byte green, byte blue, byte alpha) {
if (!hudCaching$blendEnabled && HUDCaching.renderingCacheOverride && alpha < Byte.MAX_VALUE) {
alpha = Byte.MAX_VALUE;
}
if (changeColor(ub2f(red), ub2f(green), ub2f(blue), ub2f(alpha))) {
GL11.glColor4ub(red, green, blue, alpha);
}
@@ -729,6 +744,7 @@ public class GLStateManager {
glListMode = mode;
GL11.glNewList(list, mode);
for(IStateStack<?> stack : Feature.maskToFeatures(GL11.GL_ALL_ATTRIB_BITS)) {
// Feature Stack, copy of current feature state
glListStates.put(stack, (ISettableState<?>) ((ISettableState<?>)stack).copy());
}
if(glListMode == GL11.GL_COMPILE) {
@@ -743,8 +759,10 @@ public class GLStateManager {
final Set<Map.Entry<IStateStack<?>, ISettableState<?>>> changedStates = new ObjectArraySet<>();
for(Map.Entry<IStateStack<?>, ISettableState<?>> entry : glListStates.entrySet()) {
// If the current stack state is different than the copy of the state at the start
if(!((ISettableState<?>)entry.getKey()).sameAs(entry.getValue())) {
changedStates.add(entry);
// Then we want to put into the change set the stack and the copy of the state now
changedStates.add(new AbstractMap.SimpleEntry<>(entry.getKey(), (ISettableState<?>) ((ISettableState<?>) entry.getKey()).copy()));
}
}
if(changedStates.size() != 0) {
@@ -763,10 +781,15 @@ public class GLStateManager {
}
public static void glCallList(int list) {
GL11.glCallList(list);
if(glListChanges.containsKey(list)) {
for(Map.Entry<IStateStack<?>, ISettableState<?>> entry : glListChanges.get(list)) {
((ISettableState<?>)entry.getKey()).set(entry.getValue());
if(list < 0) {
VBOManager.get(list).render();
} else {
GL11.glCallList(list);
if(glListChanges.containsKey(list)) {
for(Map.Entry<IStateStack<?>, ISettableState<?>> entry : glListChanges.get(list)) {
// Set the stack to the cached state at the end of the call list compilation
((ISettableState<?>)entry.getKey()).set(entry.getValue());
}
}
}
}
@@ -919,4 +942,8 @@ public class GLStateManager {
public static int getActiveTextureUnit() {
return activeTextureUnit.topInt();
}
public static int getListMode() {
return glListMode;
}
}
@@ -9,6 +9,8 @@ import net.minecraft.client.renderer.Tessellator;
import java.nio.ByteBuffer;
import java.util.List;
import org.lwjgl.opengl.GL11;
@SuppressWarnings("unused")
public class TessellatorManager {
private static final ThreadLocal<CapturingTessellator> capturingTessellator = ThreadLocal.withInitial(CapturingTessellator::new);
@@ -38,7 +40,9 @@ public class TessellatorManager {
public static void startCapturing() {
if(currentlyCapturing.get()) throw new IllegalStateException("Tried to start capturing when already capturing!");
if(capturingTessellator.get().getQuads().size() > 0) throw new IllegalStateException("Tried to start capturing with existing collected Quads!");
final CapturingTessellator tess = capturingTessellator.get();
if(tess.getQuads().size() > 0) throw new IllegalStateException("Tried to start capturing with existing collected Quads!");
tess.storeTranslation();
currentlyCapturing.set(true);
}
@@ -57,6 +61,7 @@ public class TessellatorManager {
final List<Quad> quads = tess.getQuads();
tess.discard();
tess.restoreTranslation();
return quads;
}
@@ -76,7 +81,7 @@ public class TessellatorManager {
* uploads the buffer to a new VertexBuffer, and clears the quads.
*/
public static VertexBuffer stopCapturingToVBO(VertexFormat format) {
return new VertexBuffer(format).upload(stopCapturingToBuffer(format));
return new VertexBuffer(format, GL11.GL_QUADS).upload(stopCapturingToBuffer(format));
}
static {
@@ -1,144 +0,0 @@
package com.gtnewhorizons.angelica.glsm.states;
import org.joml.Matrix4f;
import org.joml.Matrix4fStack;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
public class MatrixState {
public MatrixMode mode = MatrixMode.NONE;
public final Matrix4fStack projectionMatrix;
public final Matrix4fStack modelViewMatrix;
public MatrixState() {
projectionMatrix = new Matrix4fStack(GL11.glGetInteger(GL11.GL_MAX_PROJECTION_STACK_DEPTH));
modelViewMatrix = new Matrix4fStack(GL11.glGetInteger(GL11.GL_MAX_MODELVIEW_STACK_DEPTH));
}
public void identity() {
switch (mode) {
case MODELVIEW -> modelViewMatrix.identity();
case PROJECTION -> projectionMatrix.identity();
default -> {
}
}
}
public void setMode(int mode) {
switch (mode) {
case GL11.GL_MODELVIEW -> this.mode = MatrixMode.MODELVIEW;
case GL11.GL_PROJECTION -> this.mode = MatrixMode.PROJECTION;
case GL11.GL_TEXTURE -> this.mode = MatrixMode.TEXTURE;
default -> throw new RuntimeException("Unsupported matrix mode: " + mode);
}
}
public void translate(float x, float y, float z) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.translate(x, y, z);
case PROJECTION -> projectionMatrix.translate(x, y, z);
default -> {
}
}
}
public void scale(float x, float y, float z) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.scale(x, y, z);
case PROJECTION -> projectionMatrix.scale(x, y, z);
default -> {
}
}
}
private final Matrix4f tempMatrix = new Matrix4f();
public void multiply(FloatBuffer matrix) {
tempMatrix.set(matrix);
switch (mode) {
case MODELVIEW -> modelViewMatrix.mul(tempMatrix);
case PROJECTION -> projectionMatrix.mul(tempMatrix);
default -> {
}
}
}
public void multiply(Matrix4f matrix) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.mul(matrix);
case PROJECTION -> projectionMatrix.mul(matrix);
default -> {
}
}
}
public void rotate(float angle, float x, float y, float z) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.rotate(angle, x, y, z);
case PROJECTION -> projectionMatrix.rotate(angle, x, y, z);
default -> {
}
}
}
public void ortho(double left, double right, double bottom, double top, double zNear, double zFar) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.ortho((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar);
case PROJECTION -> projectionMatrix.ortho((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar);
default -> {
}
}
}
public void frustum(double left, double right, double bottom, double top, double zNear, double zFar) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.frustum((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar);
case PROJECTION -> projectionMatrix.frustum((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar);
default -> {
}
}
}
public void push() {
switch (mode) {
case MODELVIEW -> modelViewMatrix.pushMatrix();
case PROJECTION -> projectionMatrix.pushMatrix();
default -> {
}
}
}
public void pop() {
switch (mode) {
case MODELVIEW -> modelViewMatrix.popMatrix();
case PROJECTION -> projectionMatrix.popMatrix();
default -> {
}
}
}
public void perspective(float fovy, float aspect, float zNear, float zFar) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.perspective(fovy, aspect, zNear, zFar);
case PROJECTION -> projectionMatrix.perspective(fovy, aspect, zNear, zFar);
default -> {
}
}
}
enum MatrixMode {
NONE,
MODELVIEW,
PROJECTION,
TEXTURE
}
@Override
public boolean equals(Object state) {
if (this == state) return true;
if (!(state instanceof MatrixState matrixState)) return false;
return mode == matrixState.mode && projectionMatrix.equals(matrixState.projectionMatrix) && modelViewMatrix.equals(matrixState.modelViewMatrix);
}
}
@@ -1,8 +1,16 @@
package com.gtnewhorizons.angelica.hudcaching;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.TessellatorManager;
import com.gtnewhorizons.angelica.mixins.early.angelica.hudcaching.GuiIngameAccessor;
import com.gtnewhorizons.angelica.mixins.early.angelica.hudcaching.GuiIngameForgeAccessor;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent;
@@ -18,10 +26,6 @@ import net.minecraft.client.settings.KeyBinding;
import net.minecraft.client.shader.Framebuffer;
import net.minecraft.util.ChatComponentText;
import net.minecraftforge.client.GuiIngameForge;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
// See LICENSE+HUDCaching.md for license information.
@@ -29,10 +33,29 @@ public class HUDCaching {
private static final Minecraft mc = Minecraft.getMinecraft();
public static Framebuffer framebuffer;
static {
framebuffer = new Framebuffer(0, 0, true);
framebuffer.setFramebufferColor(0, 0, 0, 0);
}
private static boolean dirty = true;
public static boolean renderingCacheOverride;
public static final HUDCaching INSTANCE = new HUDCaching();
/*
* Some HUD features cause problems/inaccuracies when being rendered into cache.
* We capture those and render them later
*/
// Vignette texture has no alpha
public static boolean renderVignetteCaptured;
// Helmet & portal are chances other mods render vignette
// For example Thaumcraft renders warp effect during this
public static boolean renderHelmetCaptured;
public static float renderPortalCapturedTicks;
// Crosshairs need to be blended with the scene
public static boolean renderCrosshairsCaptured;
public static final HUDCaching INSTANCE = new HUDCaching();
private HUDCaching() {}
@@ -79,77 +102,101 @@ public class HUDCaching {
}
}
// TODO draw vignette
@SuppressWarnings("unused")
public static void renderCachedHud(EntityRenderer renderer, GuiIngame ingame, float partialTicks, boolean b, int i, int j) {
public static void renderCachedHud(EntityRenderer renderer, GuiIngame ingame, float partialTicks, boolean hasScreen, int mouseX, int mouseY) {
if (!OpenGlHelper.isFramebufferEnabled() || !isEnabled) {
ingame.renderGameOverlay(partialTicks, b, i, j);
ingame.renderGameOverlay(partialTicks, hasScreen, mouseX, mouseY);
return;
}
GLStateManager.enableDepthTest();
if (dirty) {
dirty = false;
resetFramebuffer(mc.displayWidth, mc.displayHeight);
framebuffer.bindFramebuffer(false);
renderingCacheOverride = true;
ingame.renderGameOverlay(partialTicks, hasScreen, mouseX, mouseY);
renderingCacheOverride = false;
mc.getFramebuffer().bindFramebuffer(false);
} else {
renderer.setupOverlayRendering();
}
ScaledResolution resolution = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
int width = resolution.getScaledWidth();
int height = resolution.getScaledHeight();
renderer.setupOverlayRendering();
GLStateManager.enableBlend();
if (framebuffer != null) {
Tessellator tessellator = TessellatorManager.get();
if (ingame instanceof GuiIngameForge) {
((GuiIngameForgeAccessor) ingame).callRenderCrosshairs(width, height);
} else if (GuiIngameForge.renderCrosshairs) {
mc.getTextureManager().bindTexture(Gui.icons);
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(GL11.GL_ONE_MINUS_DST_COLOR, GL11.GL_ONE_MINUS_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO);
GLStateManager.enableAlphaTest();
drawTexturedModalRect(tessellator, (width >> 1) - 7, (height >> 1) - 7);
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
// reset the color that may be applied by some items
GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
// render bits that were captured when rendering into cache
GuiIngameAccessor gui = (GuiIngameAccessor) ingame;
if (renderVignetteCaptured)
{
gui.callRenderVignette(mc.thePlayer.getBrightness(partialTicks), width, height);
} else {
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0);
}
if (ingame instanceof GuiIngameForge) {
GuiIngameForgeAccessor guiForge = ((GuiIngameForgeAccessor) ingame);
if (renderHelmetCaptured) {
guiForge.callRenderHelmet(resolution, partialTicks, hasScreen, mouseX, mouseY);
}
if (renderPortalCapturedTicks > 0) {
guiForge.callRenderPortal(width, height, partialTicks);
}
if (renderCrosshairsCaptured) {
guiForge.callRenderCrosshairs(width, height);
}
} else {
if (renderHelmetCaptured)
{
gui.callRenderPumpkinBlur(width, height);
}
if (renderPortalCapturedTicks > 0)
{
gui.callRenderPortal(renderPortalCapturedTicks, width, height);
}
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
framebuffer.bindFramebufferTexture();
drawTexturedRect(tessellator, (float) resolution.getScaledWidth_double(), (float) resolution.getScaledHeight_double());
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
}
if (framebuffer == null || dirty) {
dirty = false;
framebuffer = checkFramebufferSizes(framebuffer, mc.displayWidth, mc.displayHeight);
framebuffer.framebufferClear();
framebuffer.bindFramebuffer(false);
GLStateManager.disableBlend();
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GLStateManager.disableLighting();
GLStateManager.disableFog();
renderingCacheOverride = true;
ingame.renderGameOverlay(partialTicks, b, i, j);
renderingCacheOverride = false;
mc.getFramebuffer().bindFramebuffer(false);
GLStateManager.enableBlend();
}
GLStateManager.enableDepthTest();
// render cached frame
Tessellator tessellator = TessellatorManager.get();
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
framebuffer.bindFramebufferTexture();
drawTexturedRect(tessellator, (float) resolution.getScaledWidth_double(), (float) resolution.getScaledHeight_double());
GLStateManager.tryBlendFuncSeparate(GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
mc.getTextureManager().bindTexture(Gui.icons);
}
/**
* We are skipping certain render calls when rendering into cache,
* however, we cannot skip the GL state changes. This will fix
* the state before we start rendering
*/
public static void fixGLStateBeforeRenderingCache() {
GLStateManager.glDepthMask(true);
GLStateManager.enableDepthTest();
GLStateManager.enableAlphaTest();
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
GLStateManager.disableBlend();
}
private static Framebuffer checkFramebufferSizes(Framebuffer framebuffer, int width, int height) {
if (framebuffer == null || framebuffer.framebufferWidth != width || framebuffer.framebufferHeight != height) {
if (framebuffer == null) {
framebuffer = new Framebuffer(width, height, true);
framebuffer.framebufferColor[0] = 0.0F;
framebuffer.framebufferColor[1] = 0.0F;
framebuffer.framebufferColor[2] = 0.0F;
} else {
framebuffer.createBindFramebuffer(width, height);
}
private static void resetFramebuffer(int width, int height) {
if (framebuffer.framebufferWidth != width || framebuffer.framebufferHeight != height) {
framebuffer.createBindFramebuffer(width, height);
framebuffer.setFramebufferFilter(GL11.GL_NEAREST);
} else {
framebuffer.framebufferClear();
}
return framebuffer;
// copy depth buffer from MC
OpenGlHelper.func_153171_g(GL30.GL_READ_FRAMEBUFFER, mc.getFramebuffer().framebufferObject);
OpenGlHelper.func_153171_g(GL30.GL_DRAW_FRAMEBUFFER, framebuffer.framebufferObject);
GL30.glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT, GL11.GL_NEAREST);
}
private static void drawTexturedRect(Tessellator tessellator, float width, float height) {
@@ -166,13 +213,4 @@ public class HUDCaching {
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
}
private static void drawTexturedModalRect(Tessellator tessellator, int x, int y) {
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(x, y + 16, 100.0, 0.0, 0.0625);
tessellator.addVertexWithUV(x + 16, y + 16, 100.0, 0.0625, 0.0625);
tessellator.addVertexWithUV(x + 16, y, 100.0, 0.0625, 0.0);
tessellator.addVertexWithUV(x, y, 100.0, 0.0, 0.0);
tessellator.draw();
}
}
@@ -0,0 +1,8 @@
package com.gtnewhorizons.angelica.interfaces;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
public interface IThreadSafeISBRH extends ISimpleBlockRenderingHandler {
IThreadSafeISBRH getThreadLocal();
}
@@ -102,31 +102,6 @@ public class AngelicaTweaker implements IFMLLoadingPlugin, IEarlyMixinLoader {
return Mixins.getEarlyMixins(loadedCoreMods);
}
private List<String> getNotFineMixins(Set<String> loadedCoreMods) {
if(FMLLaunchHandler.side().isServer())
return Collections.emptyList();
final List<String> mixins = new ArrayList<>();
mixins.add("notfine.clouds.MixinEntityRenderer");
mixins.add("notfine.clouds.MixinGameSettings");
mixins.add("notfine.clouds.MixinRenderGlobal");
mixins.add("notfine.clouds.MixinWorldType");
mixins.add("notfine.leaves.MixinBlockLeaves");
mixins.add("notfine.leaves.MixinBlockLeavesBase");
mixins.add("notfine.particles.MixinBlockEnchantmentTable");
mixins.add("notfine.particles.MixinEffectRenderer");
mixins.add("notfine.particles.MixinWorldClient");
mixins.add("notfine.particles.MixinWorldProvider");
mixins.add("notfine.toggle.MixinGuiIngame");
mixins.add("notfine.toggle.MixinEntityRenderer");
mixins.add("notfine.toggle.MixinRender");
mixins.add("notfine.toggle.MixinRenderItem");
return mixins;
}
private static final ImmutableMap<String, TargetedMod> MODS_BY_CLASS = ImmutableMap.<String, TargetedMod>builder()
.put("optifine.OptiFineForgeTweaker", TargetedMod.OPTIFINE)
.put("fastcraft.Tweaker", TargetedMod.FASTCRAFT)
@@ -47,7 +47,9 @@ public enum Mixins {
ANGELICA_ENABLE_DEBUG(new Builder("Angelica Debug").addTargetedMod(TargetedMod.VANILLA).setSide(Side.CLIENT)
.setPhase(Phase.EARLY).setApplyIf(() -> AngelicaMod.lwjglDebug).addMixinClasses(
"angelica.debug.MixinSplashProgress"
"angelica.debug.MixinProfiler"
,"angelica.debug.MixinSplashProgress"
,"angelica.debug.MixinTextureManager"
)
),
@@ -79,15 +81,9 @@ public enum Mixins {
)
),
SODIUM_STARTUP(new Builder("Start Sodium").addTargetedMod(TargetedMod.VANILLA).setSide(Side.CLIENT)
.setPhase(Phase.EARLY).setApplyIf(() -> AngelicaConfig.enableSodium && !AngelicaConfig.enableIris).addMixinClasses(
"sodium.startup.MixinInitDebug"
)
),
SODIUM(new Builder("Sodium").addTargetedMod(TargetedMod.VANILLA).setSide(Side.CLIENT)
.setPhase(Phase.EARLY).setApplyIf(() -> AngelicaConfig.enableSodium).addMixinClasses(
"sodium.MixinChunkProviderClient"
"sodium.MixinChunkProviderClient"
,"sodium.MixinBlock"
,"sodium.AccessorBiomeColorEvent"
,"sodium.MixinBiomeGenBase"
@@ -113,6 +109,14 @@ public enum Mixins {
,"sodium.MixinTileEntityRendererDispatcher"
,"sodium.MixinLongHashMap"
,"sodium.MixinRender"
,"sodium.MixinRenderingRegistry"
)
),
SODIUM_DYN_SURROUND(new Builder("Sodium without Dynamic Surroundings").addTargetedMod(TargetedMod.VANILLA)
.addExcludedMod(TargetedMod.DYNAMIC_SURROUNDINGS_MIST).addExcludedMod(TargetedMod.DYNAMIC_SURROUNDINGS_ORIGINAL).setSide(Side.CLIENT)
.setPhase(Phase.EARLY).setApplyIf(() -> AngelicaConfig.enableSodium).addMixinClasses(
"sodium.MixinEntityRenderer$WeatherQuality"
)
),
@@ -159,7 +163,8 @@ public enum Mixins {
HUD_CACHING(new Builder("Renders the HUD elements 20 times per second maximum to improve performance")
.addTargetedMod(TargetedMod.VANILLA).setSide(Side.CLIENT).setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableHudCaching).addMixinClasses(
"angelica.hudcaching.GuiIngameForgeAccessor",
"angelica.hudcaching.GuiIngameAccessor",
"angelica.hudcaching.GuiIngameForgeAccessor",
"angelica.hudcaching.MixinEntityRenderer_HUDCaching",
"angelica.hudcaching.MixinFramebuffer_HUDCaching",
"angelica.hudcaching.MixinGuiIngame_HUDCaching",
@@ -169,7 +174,7 @@ public enum Mixins {
),
OPTIMIZE_WORLD_UPDATE_LIGHT(new Builder("Optimize world updateLightByType method").setPhase(Phase.EARLY)
.setSide(Side.BOTH).addTargetedMod(TargetedMod.VANILLA).setApplyIf(() -> AngelicaConfig.optimizeWorldUpdateLight)
.setSide(Side.BOTH).addTargetedMod(TargetedMod.VANILLA).addExcludedMod(TargetedMod.ARCHAICFIX).setApplyIf(() -> AngelicaConfig.optimizeWorldUpdateLight)
.addMixinClasses("angelica.lighting.MixinWorld_FixLightUpdateLag")),
@@ -186,6 +191,11 @@ public enum Mixins {
"angelica.animation.MixinWorldRenderer",
"angelica.animation.MixinRenderItem")),
SPEEDUP_CAMPFIRE_BACKPORT_ANIMATIONS(new Builder("Add animation speedup support to Campfire Backport").setPhase(Phase.LATE)
.addTargetedMod(TargetedMod.CAMPFIRE_BACKPORT).setSide(Side.CLIENT)
.setApplyIf(() -> AngelicaConfig.speedupAnimations)
.addMixinClasses("client.campfirebackport.MixinRenderBlockCampfire")),
IC2_FLUID_RENDER_FIX(new Builder("IC2 Fluid Render Fix").setPhase(Phase.EARLY).setSide(Side.CLIENT)
.addTargetedMod(TargetedMod.IC2).setApplyIf(() -> AngelicaConfig.speedupAnimations)
.addMixinClasses("angelica.textures.ic2.MixinRenderLiquidCell")),
@@ -204,12 +214,31 @@ public enum Mixins {
NOTFINE_FEATURES(new Builder("NotFine Features").addTargetedMod(TargetedMod.VANILLA).setSide(Side.CLIENT)
.setPhase(Phase.EARLY).setApplyIf(() -> AngelicaConfig.enableNotFineFeatures).addMixinClasses(
//"notfine.clouds.MixinEntityRenderer"
//,"notfine.clouds.MixinGameSettings"
//,"notfine.clouds.MixinRenderGlobal"
//,"notfine.clouds.MixinWorldType"
"notfine.glint.MixinRenderBiped"
,"notfine.glint.MixinRenderItem"
,"notfine.glint.MixinRenderPlayer"
,"notfine.gui.MixinGuiSlot"
,"notfine.leaves.MixinBlockLeaves"
,"notfine.leaves.MixinBlockLeavesBase"
//,"notfine.particles.MixinBlockEnchantmentTable"
//,"notfine.particles.MixinEffectRenderer"
//,"notfine.particles.MixinWorldClient"
//,"notfine.particles.MixinWorldProvider"
,"notfine.renderer.MixinRenderGlobal"
,"notfine.settings.MixinGameSettings"
//,"notfine.toggle.MixinGuiIngame"
//,"notfine.toggle.MixinEntityRenderer"
//,"notfine.toggle.MixinRender" --> No Sodium below
//,"notfine.toggle.MixinRenderItem"
)),
NOTFINE_FEATURES_NO_SODIUM(new Builder("NotFine Features").addTargetedMod(TargetedMod.VANILLA).setSide(Side.CLIENT)
.setPhase(Phase.EARLY).setApplyIf(() -> AngelicaConfig.enableNotFineFeatures && !AngelicaConfig.enableSodium).addMixinClasses(
"notfine.toggle.MixinRender"
)),
NOTFINE_FEATURES_NO_MCPF_CIT(new Builder("NotFine Features which clash with mcpf cit (compat handled in MCPF_NF mixin)").addTargetedMod(TargetedMod.VANILLA).setSide(Side.CLIENT)
@@ -220,7 +249,7 @@ public enum Mixins {
"notfine.glint.MixinRenderItemGlint"
)),
NOTFINE_LATE_TWILIGHT_FORESTLEAVES(new Builder("NotFine Mod Leaves").addTargetedMod(TargetedMod.TWILIGHT_FOREST).setSide(Side.CLIENT)
NOTFINE_LATE_TWILIGHT_FOREST_LEAVES(new Builder("NotFine Mod Leaves").addTargetedMod(TargetedMod.TWILIGHT_FOREST).setSide(Side.CLIENT)
.setPhase(Phase.LATE).setApplyIf(() -> AngelicaConfig.enableNotFineFeatures).addMixinClasses(
"notfine.leaves.twilightforest.MixinBlockTFLeaves"
,"notfine.leaves.twilightforest.MixinBlockTFLeaves3"
@@ -7,9 +7,13 @@ public enum TargetedMod {
VANILLA("Minecraft", null)
, FASTCRAFT("FastCraft", "fastcraft.Tweaker")
, OPTIFINE("Optifine", "optifine.OptiFineForgeTweaker", "Optifine")
, ARCHAICFIX("ArchaicFix", "org.embeddedt.archaicfix.ArchaicCore", "archaicfix")
, BOTANIA("Botania", null, "Botania")
, CAMPFIRE_BACKPORT("CampfireBackport", null, "campfirebackport")
, CHICKENCHUNKS("ChickenChunks", null, "ChickenChunks")
, COFHCORE("CoFHCore", "cofh.asm.LoadingPlugin", "CoFHCore")
, DYNAMIC_SURROUNDINGS_MIST("Dynamic Surroundings", "org.blockartistry.mod.DynSurround.mixinplugin.DynamicSurroundingsEarlyMixins", "dsurround")
, DYNAMIC_SURROUNDINGS_ORIGINAL("Dynamic Surroundings", "org.blockartistry.mod.DynSurround.asm.TransformLoader", "dsurround")
, EXTRAUTILS("ExtraUtilities", null, "ExtraUtilities")
, GTNHLIB("GTNHLib", "com.gtnewhorizon.gtnhlib.core.GTNHLibCore", "gtnhlib")
, IC2("IC2", "ic2.core.coremod.IC2core", "IC2")
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.animation;
import com.gtnewhorizons.angelica.mixins.interfaces.IPatchedTextureAtlasSprite;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
@@ -21,6 +22,10 @@ public class MixinMinecraftForgeClient {
@Inject(method = "getItemRenderer", at = @At("HEAD"), remap = false)
private static void angelica$beforeRenderItem(ItemStack itemStack, IItemRenderer.ItemRenderType type,
CallbackInfoReturnable<IItemRenderer> cir) {
// Don't animate items if a world is not present (e.g. during loading)
if (Minecraft.getMinecraft().theWorld == null) {
return;
}
final Item item = itemStack.getItem();
if (item.requiresMultipleRenderPasses()) {
for (int i = 0; i < item.getRenderPasses(itemStack.getItemDamage()); i++) {
@@ -66,6 +66,14 @@ public class MixinRenderBlocks implements ITexturesCache {
return icon;
}
@Inject(method = "drawCrossedSquares", at = @At("HEAD"))
public void angelica$markCrossedSquaresAnimationForUpdate(IIcon icon, double p_147765_2_, double p_147765_4_, double p_147765_6_, float p_147765_8_,
CallbackInfo ci) {
AnimationsRenderUtils.markBlockTextureForUpdate(icon, blockAccess);
this.renderedSprites.add(icon);
}
@Override
public Set<IIcon> getRenderedTextures() {
@@ -0,0 +1,21 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.debug;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import net.minecraft.profiler.Profiler;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Profiler.class)
public class MixinProfiler {
@Inject(method = "startSection(Ljava/lang/String;)V", at = @At("HEAD"))
private void debugStartSection(String name, CallbackInfo ci) {
GLDebug.pushGroup("minecraft:" + name);
}
@Inject(method = "endSection()V", at = @At("HEAD"))
private void debugEndSection(CallbackInfo ci) {
GLDebug.popGroup();
}
}
@@ -0,0 +1,25 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.debug;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(TextureManager.class)
public class MixinTextureManager {
@Inject(method = "loadTexture", at = @At("RETURN"))
private void onTextureLoad(ResourceLocation resource, ITextureObject texture, CallbackInfoReturnable<Boolean> cir) {
if(texture != null && texture != TextureUtil.missingTexture) {
final int curId = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getGlTextureId());
GLDebug.nameObject(GL11.GL_TEXTURE, texture.getGlTextureId(), resource.toString());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, curId);
}
}
}
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.fontrenderer;
import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.texture.TextureManager;
@@ -15,6 +16,7 @@ import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Random;
@@ -125,12 +127,30 @@ public abstract class MixinFontRenderer implements FontRendererAccessor {
}
/**
* @author eigenraven
* @reason Replace with more sensible batched rendering and optimize some operations
* Only allow using the batched renderer if we are not in an OpenGL Display List
* Batched font renderer is not compatible with display lists, and won't really
* help performance when display lists are already being used anyway.
*/
@Overwrite
public int drawString(String text, int x, int y, int argb, boolean dropShadow)
@Inject(method = "drawString(Ljava/lang/String;IIIZ)I", at = @At("HEAD"), cancellable = true)
public void angelica$BatchedFontRendererDrawString(String text, int x, int y, int argb, boolean dropShadow, CallbackInfoReturnable<Integer> cir)
{
if (GLStateManager.getListMode() == 0) {
cir.setReturnValue(angelica$drawStringBatched(text, x, y, argb, dropShadow));
}
}
/**
* See above explanation about batched renderer in display lists.
*/
@Inject(method = "renderString", at = @At("HEAD"), cancellable = true)
public void angelica$BatchedFontRendererRenderString(String text, int x, int y, int argb, boolean dropShadow, CallbackInfoReturnable<Integer> cir) {
if (GLStateManager.getListMode() == 0) {
cir.setReturnValue(angelica$drawStringBatched(text, x, y, argb, dropShadow));
}
}
@Override
public int angelica$drawStringBatched(String text, int x, int y, int argb, boolean dropShadow) {
if (text == null)
{
return 0;
@@ -158,15 +178,6 @@ public abstract class MixinFontRenderer implements FontRendererAccessor {
}
}
/**
* @author eigenraven
* @reason Replace with more sensible batched rendering and optimize some operations
*/
@Overwrite
public int renderString(String text, int x, int y, int argb, boolean dropShadow) {
return drawString(text, x, y, argb, dropShadow);
}
@Override
public BatchingFontRenderer angelica$getBatcher() {
return angelica$batcher;
@@ -0,0 +1,18 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.hudcaching;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
import net.minecraft.client.gui.GuiIngame;
@Mixin(GuiIngame.class)
public interface GuiIngameAccessor {
@Invoker
void callRenderVignette(float brightness, int width, int height);
@Invoker
void callRenderPumpkinBlur(int width, int height);
@Invoker("func_130015_b")
void callRenderPortal(float partialTicks, int width, int height);
}
@@ -1,12 +1,24 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.hudcaching;
import net.minecraftforge.client.GuiIngameForge;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.GuiIngameForge;
@Mixin(GuiIngameForge.class)
public interface GuiIngameForgeAccessor {
@Invoker(remap = false)
void callRenderCrosshairs(int width, int height);
@Invoker(remap = false)
void callRenderHelmet(ScaledResolution res, float partialTicks, boolean hasScreen, int mouseX, int mouseY);
@Invoker(remap = false)
void callRenderPortal(int width, int height, float partialTicks);
@Invoker(remap = false)
void callBind(ResourceLocation res);
}
@@ -1,19 +1,58 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.hudcaching;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import net.minecraftforge.client.GuiIngameForge;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import net.minecraft.client.gui.Gui;
import net.minecraftforge.client.GuiIngameForge;
@Mixin(GuiIngameForge.class)
public class MixinGuiIngameForge_HUDCaching {
@Inject(method = "renderCrosshairs", at = @At("HEAD"), cancellable = true, remap = false)
private void angelica$cancelCrosshair(CallbackInfo ci) {
@Inject(method = "renderGameOverlay", at = @At("HEAD"))
private void angelica$resetCaptures(CallbackInfo ci) {
if (HUDCaching.renderingCacheOverride) {
ci.cancel();
HUDCaching.renderVignetteCaptured = false;
HUDCaching.renderHelmetCaptured = false;
HUDCaching.renderPortalCapturedTicks = -1;
HUDCaching.renderCrosshairsCaptured = false;
}
}
@Inject(method = "renderCrosshairs", at = @At("HEAD"), cancellable = true, remap = false)
private void angelica$captureRenderCrosshair(CallbackInfo ci) {
if (HUDCaching.renderingCacheOverride) {
HUDCaching.renderCrosshairsCaptured = true;
HUDCaching.fixGLStateBeforeRenderingCache();
ci.cancel();
}
}
@Inject(method = "renderHelmet", at = @At("HEAD"), cancellable = true, remap = false)
private void angelica$captureRenderHelmet(CallbackInfo ci) {
if (HUDCaching.renderingCacheOverride) {
HUDCaching.renderHelmetCaptured = true;
ci.cancel();
}
}
@Inject(method = "renderPortal", at = @At("HEAD"), cancellable = true, remap = false)
private void angelica$captureRenderPortal(int width, int height, float partialTicks, CallbackInfo ci) {
if (HUDCaching.renderingCacheOverride) {
HUDCaching.renderPortalCapturedTicks = partialTicks;
ci.cancel();
}
}
@Inject(method = "renderBossHealth", at = @At("HEAD"))
private void angelica$bindBossHealthTexture(CallbackInfo ci) {
// boss health texture is bind in renderCrosshairs
// but HUD caching skips rendering crosshairs when rendering into cache
if (HUDCaching.renderingCacheOverride) {
((GuiIngameForgeAccessor) this).callBind(Gui.icons);
}
}
}
@@ -1,19 +1,61 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.hudcaching;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import net.minecraft.client.gui.GuiIngame;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiIngame;
@Mixin(GuiIngame.class)
public class MixinGuiIngame_HUDCaching {
@Inject(method = "renderVignette", at = @At("HEAD"), cancellable = true)
private void angelica$cancelVignette(CallbackInfo ci) {
@Inject(method = "renderGameOverlay", at = @At("HEAD"))
private void angelica$resetCaptures(CallbackInfo ci) {
if (HUDCaching.renderingCacheOverride) {
ci.cancel();
HUDCaching.renderVignetteCaptured = false;
HUDCaching.renderHelmetCaptured = false;
HUDCaching.renderPortalCapturedTicks = -1;
// GuiIngame doesn't allow a clean way to capture crosshair
}
}
@Inject(method = "renderVignette", at = @At("HEAD"), cancellable = true)
private void angelica$captureRenderVignette(CallbackInfo ci) {
if (HUDCaching.renderingCacheOverride) {
HUDCaching.renderVignetteCaptured = true;
ci.cancel();
}
}
@Inject(method = "renderPumpkinBlur", at = @At("HEAD"), cancellable = true)
private void angelica$captureRenderPumpkimBlur(CallbackInfo ci) {
if (HUDCaching.renderingCacheOverride) {
HUDCaching.renderHelmetCaptured = true;
ci.cancel();
}
}
@Inject(method = "func_130015_b", at = @At("HEAD"), cancellable = true)
private void angelica$captureRenderPortal(float partialTicks, int width, int height, CallbackInfo ci) {
if (HUDCaching.renderingCacheOverride) {
HUDCaching.renderPortalCapturedTicks = partialTicks;
ci.cancel();
}
}
@WrapOperation(method = "func_96136_a", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/FontRenderer;drawString(Ljava/lang/String;III)I"))
private int angelica$fixScoreboardTextAlpha(FontRenderer fontRenderer, String text, int x, int y, int color, Operation<Integer> op) {
// Vanilla uses 0x20 for the alpha but it looks like 0xFF for some reason
// here we just make it 0xFF so it doesn't cause issues
if (HUDCaching.renderingCacheOverride) {
color |= 0xFF000000;
}
return op.call(fontRenderer, text, x, y, color);
}
}
@@ -4,7 +4,6 @@ import com.gtnewhorizons.angelica.compat.mojang.DefaultVertexFormat;
import com.gtnewhorizons.angelica.glsm.TessellatorManager;
import com.gtnewhorizons.angelica.glsm.VBOManager;
import net.minecraft.client.model.ModelRenderer;
import org.lwjgl.opengl.GL11;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
@@ -29,13 +28,4 @@ public class MixinModelRenderer {
public void stopCapturingVBO() {
VBOManager.registerVBO(this.displayList, TessellatorManager.stopCapturingToVBO(DefaultVertexFormat.POSITION_TEXTURE_NORMAL));
}
@Redirect(method = "render", at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glCallList(I)V", remap = false))
public void renderVBO(int list) {
VBOManager.get(list).render(GL11.GL_QUADS);
}
@Redirect(method = "renderWithRotation", at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glCallList(I)V", remap = false))
public void renderWithRotationVBO(int list) {
VBOManager.get(list).render(GL11.GL_QUADS);
}
}
@@ -4,7 +4,6 @@ import com.gtnewhorizons.angelica.compat.mojang.DefaultVertexFormat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.TessellatorManager;
import com.gtnewhorizons.angelica.glsm.VBOManager;
import com.gtnewhorizons.angelica.mixins.interfaces.IRenderGlobalVBOCapture;
import com.gtnewhorizons.angelica.render.CloudRenderer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
@@ -12,7 +11,6 @@ import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.Tessellator;
import net.minecraftforge.client.IRenderHandler;
import org.lwjgl.opengl.GL11;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
@@ -20,7 +18,7 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(value = RenderGlobal.class)
public class MixinRenderGlobal implements IRenderGlobalVBOCapture {
public class MixinRenderGlobal {
@Shadow public int starGLCallList;
@Shadow private int glSkyList;
@Shadow private int glSkyList2;
@@ -38,13 +36,10 @@ public class MixinRenderGlobal implements IRenderGlobalVBOCapture {
return VBOManager.generateDisplayLists(range);
}
@Override
@Redirect(method="<init>", at = @At(value="INVOKE", target="Lorg/lwjgl/opengl/GL11;glNewList(II)V", ordinal = 0), remap = false)
public void startStarsVBO(int list, int mode) {
TessellatorManager.startCapturing();
}
@Override
@Redirect(method="<init>", at = @At(value="INVOKE", target="Lorg/lwjgl/opengl/GL11;glEndList()V", ordinal = 0), remap = false)
public void finishStarsVBO() {
VBOManager.registerVBO(starGLCallList, TessellatorManager.stopCapturingToVBO(DefaultVertexFormat.POSITION));
@@ -56,35 +51,26 @@ public class MixinRenderGlobal implements IRenderGlobalVBOCapture {
return TessellatorManager.get();
}
@Override
@Redirect(method="<init>", at = @At(value="INVOKE", target="Lorg/lwjgl/opengl/GL11;glNewList(II)V", ordinal = 1), remap = false)
public void startSkyVBO(int list, int mode) {
// Do nothing, we'll be making a VBO instead.
// Do nothing, we'll be making a VBO instead and already started the capturing above
}
@Override
@Redirect(method="<init>", at = @At(value="INVOKE", target="Lorg/lwjgl/opengl/GL11;glEndList()V", ordinal = 1), remap = false)
public void finishSkyVBO() {
VBOManager.registerVBO(glSkyList, TessellatorManager.stopCapturingToVBO(DefaultVertexFormat.POSITION));
}
@Override
@Redirect(method="<init>", at = @At(value="INVOKE", target="Lorg/lwjgl/opengl/GL11;glNewList(II)V", ordinal = 2), remap = false)
public void startSky2VBO(int list, int mode) {
TessellatorManager.startCapturing();
}
@Override
@Redirect(method="<init>", at = @At(value="INVOKE", target="Lorg/lwjgl/opengl/GL11;glEndList()V", ordinal = 2), remap = false)
public void finishSky2VBO() {
VBOManager.registerVBO(glSkyList2, TessellatorManager.stopCapturingToVBO(DefaultVertexFormat.POSITION));
}
@Redirect(method="renderSky(F)V", at = @At(value="INVOKE", target="Lorg/lwjgl/opengl/GL11;glCallList(I)V"), remap = false)
public void renderSky(int list) {
VBOManager.get(list).render(GL11.GL_QUADS);
}
/**
* @author mitchej123
* @reason VBO Clouds
@@ -6,11 +6,14 @@ import com.gtnewhorizons.angelica.compat.mojang.VertexBuffer;
import com.gtnewhorizons.angelica.compat.mojang.VertexFormat;
import com.gtnewhorizons.angelica.glsm.TessellatorManager;
import com.gtnewhorizons.angelica.mixins.interfaces.IModelCustomExt;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.Tessellator;
import net.minecraftforge.client.model.obj.GroupObject;
import net.minecraftforge.client.model.obj.WavefrontObject;
import org.lwjgl.opengl.GL11;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
@@ -45,7 +48,16 @@ public abstract class MixinWavefrontObject implements IModelCustomExt {
if(vertexBuffer == null) {
rebuildVBO();
}
vertexBuffer.render(GL11.GL_QUADS);
vertexBuffer.render();
}
/**
* @author mitchej123
* @reason Force all models to use VBOs
*/
@SideOnly(Side.CLIENT)
@Overwrite
public void renderAll() {
renderAllVBO();
}
}
@@ -2,19 +2,79 @@ package com.gtnewhorizons.angelica.mixins.early.notfine.renderer;
import jss.notfine.core.Settings;
import jss.notfine.render.RenderStars;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.Tessellator;
import net.minecraftforge.client.IRenderHandler;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.llamalad7.mixinextras.injector.WrapWithCondition;
@Mixin(value = RenderGlobal.class)
public abstract class MixinRenderGlobal {
@Inject(method = "renderSky", at = @At("HEAD"), cancellable = true)
void notFine$toggleSky(CallbackInfo ci) {
if(!(boolean)Settings.MODE_SKY.option.getStore()) ci.cancel();
@Shadow private int glSkyList;
@Shadow private int starGLCallList;
@Shadow private int glSkyList2;
@WrapWithCondition(
method = "renderSky(F)V",
at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glCallList(I)V", remap = false))
private boolean conditionalCallList(int i) {
if(i == starGLCallList) {
return (boolean)Settings.MODE_STARS.option.getStore();
} else {
return (boolean)Settings.MODE_SKY.option.getStore();
}
}
@WrapWithCondition(
method = "renderSky(F)V",
at = @At(value = "INVOKE", target = "Lnet/minecraftforge/client/IRenderHandler;render(FLnet/minecraft/client/multiplayer/WorldClient;Lnet/minecraft/client/Minecraft;)V", remap = false))
private boolean conditionalRenderHandlerRender(IRenderHandler irh, float f, WorldClient wc, Minecraft mc) {
return (boolean)Settings.MODE_SKY.option.getStore();
}
@Inject(method="renderSky(F)V", at=@At(value="INVOKE", target="Lnet/minecraft/client/renderer/Tessellator;draw()I", ordinal = 0))
private void conditionalTessellatorDrawEndSkybox(CallbackInfo ci) {
if(!(boolean)Settings.MODE_SKY.option.getStore()) {
Tessellator.instance.vertexCount = 0;
}
}
@Inject(method="renderSky(F)V", at=@At(value="INVOKE", target="Lnet/minecraft/client/renderer/Tessellator;draw()I", ordinal = 1))
private void conditionalTessellatorDrawSunsetSunrise(CallbackInfo ci) {
if(!(boolean)Settings.MODE_SKY.option.getStore()) {
Tessellator.instance.vertexCount = 0;
}
}
@Inject(method="renderSky(F)V", at=@At(value="INVOKE", target="Lnet/minecraft/client/renderer/Tessellator;draw()I", ordinal = 2))
private void conditionalTessellatorDrawSun(CallbackInfo ci) {
if(!(boolean)Settings.MODE_SUN_MOON.option.getStore()) {
Tessellator.instance.vertexCount = 0;
}
}
@Inject(method="renderSky(F)V", at=@At(value="INVOKE", target="Lnet/minecraft/client/renderer/Tessellator;draw()I", ordinal = 3))
private void conditionalTessellatorDrawMoon(CallbackInfo ci) {
if(!(boolean)Settings.MODE_SUN_MOON.option.getStore()) {
Tessellator.instance.vertexCount = 0;
}
}
@Inject(method="renderSky(F)V", at=@At(value="INVOKE", target="Lnet/minecraft/client/renderer/Tessellator;draw()I", ordinal = 4))
private void conditionalTessellatorDrawHorizon(CallbackInfo ci) {
if(!(boolean)Settings.MODE_SKY.option.getStore()) {
Tessellator.instance.vertexCount = 0;
}
}
/**
@@ -3,7 +3,6 @@ package com.gtnewhorizons.angelica.mixins.early.shaders.startup;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.loading.AngelicaTweaker;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.GLDebug;
import net.coderbot.iris.gl.IrisRenderSystem;
import net.minecraft.client.renderer.OpenGlHelper;
import org.spongepowered.asm.mixin.Mixin;
@@ -20,8 +19,6 @@ public class MixinInitRenderer {
return;
}
Iris.identifyCapabilities();
GLDebug.initRenderer();
IrisRenderSystem.initRenderer();
Iris.onRenderSystemInit();
}
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.mixins.early.sodium;
import com.gtnewhorizons.angelica.utils.EventUtils;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraftforge.event.terraingen.BiomeEvent;
import org.spongepowered.asm.mixin.Mixin;
@@ -19,6 +20,7 @@ public class MixinBiomeGenBase {
@Unique
private void prepareEvent(BiomeEvent.BiomeColor event, int defaultColor) {
event.newColor = defaultColor;
EventUtils.clearPhase(event);
((AccessorBiomeColorEvent)event).setOriginalColor(defaultColor);
}
@@ -0,0 +1,21 @@
package com.gtnewhorizons.angelica.mixins.early.sodium;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.settings.GameSettings;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
/**
* Dynamic surroundings overwrites the method resulting in a clash
*/
@Mixin(EntityRenderer.class)
public abstract class MixinEntityRenderer$WeatherQuality {
@Redirect(method = "renderRainSnow(F)V", at = @At(value = "FIELD", target = "Lnet/minecraft/client/settings/GameSettings;fancyGraphics:Z", opcode = Opcodes.GETFIELD))
protected boolean redirectGetFancyWeather(GameSettings settings) {
return SodiumClientMod.options().quality.weatherQuality.isFancy();
}
}
@@ -1,15 +1,11 @@
package com.gtnewhorizons.angelica.mixins.early.sodium;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import me.jellysquid.mods.sodium.client.gl.compat.FogHelper;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.settings.GameSettings;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(EntityRenderer.class)
@@ -23,8 +19,4 @@ public class MixinEntityRenderer {
FogHelper.blue = fogColorBlue;
}
@Redirect(method = "renderRainSnow(F)V", at = @At(value = "FIELD", target = "Lnet/minecraft/client/settings/GameSettings;fancyGraphics:Z", opcode = Opcodes.GETFIELD))
protected boolean redirectGetFancyWeather(GameSettings settings) {
return SodiumClientMod.options().quality.weatherQuality.isFancy();
}
}
@@ -0,0 +1,32 @@
package com.gtnewhorizons.angelica.mixins.early.sodium;
import com.gtnewhorizons.angelica.interfaces.IThreadSafeISBRH;
import com.gtnewhorizons.angelica.mixins.interfaces.IRenderingRegistryExt;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import cpw.mods.fml.client.registry.RenderingRegistry;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import java.util.Map;
@Mixin(value = RenderingRegistry.class, remap = false)
public class MixinRenderingRegistry implements IRenderingRegistryExt {
@Shadow private Map<Integer, ISimpleBlockRenderingHandler> blockRenderers;
@Override
public ISimpleBlockRenderingHandler getISBRH(int modelId) {
return this.blockRenderers.get(modelId);
}
@WrapOperation(method = { "renderWorldBlock", "renderInventoryBlock", "renderItemAsFull3DBlock" }, at = @At(value="INVOKE", target="Ljava/util/Map;get(Ljava/lang/Object;)Ljava/lang/Object;"))
private Object getWrapped(Map<Integer, ISimpleBlockRenderingHandler> instance, Object modelId, Operation<ISimpleBlockRenderingHandler> original) {
final ISimpleBlockRenderingHandler res = original.call(instance, modelId);
if(res instanceof IThreadSafeISBRH isbhr) {
return isbhr.getThreadLocal();
}
return res;
}
}
@@ -1,26 +0,0 @@
package com.gtnewhorizons.angelica.mixins.early.sodium.startup;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.loading.AngelicaTweaker;
import net.coderbot.iris.Iris;
import net.minecraft.client.renderer.OpenGlHelper;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(OpenGlHelper.class)
public class MixinInitDebug {
@Inject(method = "initializeTextures", at = @At("RETURN"))
private static void sodium$initIrisDebug(CallbackInfo ci) {
if (Thread.currentThread() != GLStateManager.getMainThread()) {
AngelicaTweaker.LOGGER.warn("Renderer initialization called from non-main thread!");
return;
}
// Temp -- move this into common debug code
Iris.identifyCapabilities();
Iris.setDebug(AngelicaMod.lwjglDebug);
}
}
@@ -4,6 +4,9 @@ import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer;
import net.minecraft.util.ResourceLocation;
public interface FontRendererAccessor {
int angelica$drawStringBatched(String text, int x, int y, int argb, boolean dropShadow);
BatchingFontRenderer angelica$getBatcher();
void angelica$bindTexture(ResourceLocation location);
@@ -1,14 +0,0 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
public interface IRenderGlobalVBOCapture {
void startStarsVBO(int list, int mode);
void finishStarsVBO();
void startSkyVBO(int list, int mode);
void finishSkyVBO();
void startSky2VBO(int list, int mode);
void finishSky2VBO();
}
@@ -0,0 +1,7 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
public interface IRenderingRegistryExt {
ISimpleBlockRenderingHandler getISBRH(int modelId);
}
@@ -0,0 +1,35 @@
package com.gtnewhorizons.angelica.mixins.late.client.campfirebackport;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyArgs;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.invoke.arg.Args;
import com.gtnewhorizons.angelica.mixins.interfaces.ITexturesCache;
import com.gtnewhorizons.angelica.utils.AnimationsRenderUtils;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.util.IIcon;
@Mixin(targets = "connor135246.campfirebackport.client.rendering.RenderBlockCampfire", remap = false)
public class MixinRenderBlockCampfire {
@Inject(method = "renderFace", at = @At("HEAD"))
private static void angelica$beforeRenderFace(double x, double y, double z, Block block, RenderBlocks renderer, IIcon icon, int side, CallbackInfo ci) {
AnimationsRenderUtils.markBlockTextureForUpdate(icon, renderer.blockAccess);
((ITexturesCache)renderer).getRenderedTextures().add(icon);
}
@ModifyArgs(method = "renderFire", at = @At(value = "INVOKE", target = "Lconnor135246/campfirebackport/client/rendering/RenderBlockCampfire;drawCrossedSquaresTwoIcons(Lnet/minecraft/util/IIcon;Lnet/minecraft/util/IIcon;DDDF)V"))
private static void angelica$onDrawCrossedSquaresTwoIcons(Args args, double x, double y, double z, Block block, RenderBlocks renderer, boolean mix) {
IIcon icon1 = (IIcon)args.get(0);
AnimationsRenderUtils.markBlockTextureForUpdate(icon1, renderer.blockAccess);
((ITexturesCache)renderer).getRenderedTextures().add(icon1);
IIcon icon2 = (IIcon)args.get(1);
AnimationsRenderUtils.markBlockTextureForUpdate(icon2, renderer.blockAccess);
((ITexturesCache)renderer).getRenderedTextures().add(icon2);
}
}
@@ -61,7 +61,6 @@ public class ClientProxy extends CommonProxy {
Iris.INSTANCE.fmlInitEvent();
FMLCommonHandler.instance().bus().register(Iris.INSTANCE);
MinecraftForge.EVENT_BUS.register(Iris.INSTANCE);
}
}
@@ -333,7 +333,7 @@ public class CloudRenderer implements IResourceManagerReloadListener {
// Depth pass to prevent insides rendering from the outside.
GLStateManager.glColorMask(false, false, false, false);
vbo.draw(GL11.GL_QUADS);
vbo.draw();
// Full render.
if (!mc.gameSettings.anaglyph) {
@@ -356,14 +356,14 @@ public class CloudRenderer implements IResourceManagerReloadListener {
GLStateManager.disableTexture();
GLStateManager.glDepthMask(false);
GLStateManager.disableFog();
vbo.draw(GL11.GL_QUADS);
vbo.draw();
GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL);
GLStateManager.glDepthMask(true);
GLStateManager.enableTexture();
GLStateManager.enableFog();
}
vbo.draw(GL11.GL_QUADS);
vbo.draw();
vbo.cleanupState(); // Unbind buffer and disable pointers.
// Disable our coloring.
@@ -1,5 +1,10 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.interfaces.IThreadSafeISBRH;
import com.gtnewhorizons.angelica.mixins.interfaces.IRenderingRegistryExt;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.versioning.ComparableVersion;
import it.unimi.dsi.fastutil.objects.Reference2BooleanMap;
import it.unimi.dsi.fastutil.objects.Reference2BooleanOpenHashMap;
import net.minecraft.block.Block;
@@ -7,41 +12,45 @@ import net.minecraft.block.Block;
import java.util.concurrent.locks.StampedLock;
public class AngelicaBlockSafetyRegistry {
private static final Reference2BooleanMap<Block> SAFETY_MAP = new Reference2BooleanOpenHashMap<>();
private static final Reference2BooleanMap<Block> BLOCK_SAFETY_MAP = new Reference2BooleanOpenHashMap<>();
private static final Reference2BooleanMap<Block> ISBRH_SAFETY_MAP = new Reference2BooleanOpenHashMap<>();
private static final StampedLock LOCK = new StampedLock();
public static boolean canBlockRenderOffThread(Block block) {
public static boolean canBlockRenderOffThread(Block block, boolean checkISBRH) {
final long stamp = LOCK.readLock();
final Reference2BooleanMap<Block> map = checkISBRH ? ISBRH_SAFETY_MAP : BLOCK_SAFETY_MAP;
boolean isOffThread, shouldPopulate;
try {
isOffThread = SAFETY_MAP.getBoolean(block);
isOffThread = map.getBoolean(block);
if (isOffThread) {
return true; // no need to check if 'false' was due to not being populated
}
shouldPopulate = !SAFETY_MAP.containsKey(block);
shouldPopulate = !map.containsKey(block);
} finally {
LOCK.unlock(stamp);
}
if(shouldPopulate) {
isOffThread = populateCanRenderOffThread(block);
isOffThread = populateCanRenderOffThread(block, map);
}
return isOffThread;
}
private static boolean populateCanRenderOffThread(Block block) {
final boolean canBeOffThread = !(block.getClass().getName().startsWith("gregtech."));
private static boolean populateCanRenderOffThread(Block block, Reference2BooleanMap<Block> map) {
@SuppressWarnings("deprecation")
final boolean canBeOffThread = map == ISBRH_SAFETY_MAP ? ((IRenderingRegistryExt)RenderingRegistry.instance()).getISBRH(block.getRenderType()) instanceof IThreadSafeISBRH : !(block.getClass().getName().startsWith("gregtech."));
final long stamp = LOCK.writeLock();
try {
SAFETY_MAP.put(block, canBeOffThread);
map.put(block, canBeOffThread);
} finally {
LOCK.unlock(stamp);
}
return canBeOffThread;
}
}
@@ -34,7 +34,8 @@ import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static com.gtnewhorizons.angelica.transform.BlockTransformer.*;
import static com.gtnewhorizons.angelica.transform.BlockTransformer.BlockBoundsFields;
import static com.gtnewhorizons.angelica.transform.BlockTransformer.BlockClass;
/**
* This transformer redirects all Tessellator.instance field accesses to go through our TessellatorManager.
@@ -88,6 +89,7 @@ public class RedirectorTransformer implements IClassTransformer {
glCapRedirects.put(org.lwjgl.opengl.GL11.GL_TEXTURE_2D, "Texture");
glCapRedirects.put(org.lwjgl.opengl.GL11.GL_FOG, "Fog");
glCapRedirects.put(org.lwjgl.opengl.GL12.GL_RESCALE_NORMAL, "RescaleNormal");
glCapRedirects.put(org.lwjgl.opengl.GL11.GL_SCISSOR_TEST, "ScissorTest");
methodRedirects.put(GL11, RedirectMap.newMap()
.add("glGetFloat")
.add("glAlphaFunc")
@@ -0,0 +1,28 @@
package com.gtnewhorizons.angelica.utils;
import cpw.mods.fml.common.eventhandler.Event;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.relauncher.ReflectionHelper;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
public class EventUtils {
private static final MethodHandle EVENT_PHASE;
static {
try {
EVENT_PHASE = MethodHandles.publicLookup().unreflectSetter(ReflectionHelper.findField(Event.class, "phase"));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static void clearPhase(Event e) {
try {
EVENT_PHASE.invokeExact(e, (EventPriority)null);
} catch(Throwable ex) {
throw new RuntimeException(ex);
}
}
}
+3 -1
View File
@@ -84,7 +84,9 @@ public enum Settings {
SettingsManager.shadowsUpdated();
}
},
MODE_SKY(new NotFineOptionTickBox(true, OptionImpact.MEDIUM)),
MODE_SKY(new NotFineOptionTickBox(true, OptionImpact.LOW)),
MODE_STARS(new NotFineOptionTickBox(true, OptionImpact.LOW)),
MODE_SUN_MOON(new NotFineOptionTickBox(true, OptionImpact.LOW)),
MODE_WATER(new NotFineOptionCycling<>(GraphicsQuality.DEFAULT, OptionImpact.LOW)) {
@Override
public void applyChanges() {
@@ -1,20 +1,21 @@
package jss.notfine.render;
import com.gtnewhorizons.angelica.mixins.interfaces.IRenderGlobalVBOCapture;
import com.gtnewhorizons.angelica.compat.mojang.DefaultVertexFormat;
import com.gtnewhorizons.angelica.glsm.TessellatorManager;
import com.gtnewhorizons.angelica.glsm.VBOManager;
import jss.notfine.core.Settings;
import jss.util.RandomXoshiro256StarStar;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.Tessellator;
import org.lwjgl.opengl.GL11;
public class RenderStars {
//private static final ResourceLocation locationStarsPng = new ResourceLocation("textures/colormap/stars.png");
public static void reloadStarRenderList(RenderGlobal render) {
((IRenderGlobalVBOCapture)render).startStarsVBO(render.starGLCallList, GL11.GL_COMPILE);
TessellatorManager.startCapturing();
renderStars();
((IRenderGlobalVBOCapture)render).finishStarsVBO();
VBOManager.registerVBO(render.starGLCallList, TessellatorManager.stopCapturingToVBO(DefaultVertexFormat.POSITION));
}
public static void renderStars() {
@@ -0,0 +1,23 @@
package me.flashyreese.mods.reeses_sodium_options.client.gui;
import me.jellysquid.mods.sodium.client.gui.options.Option;
import me.jellysquid.mods.sodium.client.util.Dim2i;
public interface OptionExtended<T> extends Option<T> {
boolean isHighlight();
void setHighlight(boolean highlight);
Dim2i getDim2i();
void setDim2i(Dim2i dim2i);
Dim2i getParentDimension();
void setParentDimension(Dim2i dim2i);
boolean isSelected();
void setSelected(boolean selected);
}
@@ -0,0 +1,300 @@
package me.flashyreese.mods.reeses_sodium_options.client.gui;
import com.gtnewhorizons.angelica.compat.mojang.Element;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import jss.notfine.gui.GuiCustomMenu;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.AbstractFrame;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.BasicFrame;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.components.SearchTextFieldComponent;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.tab.Tab;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.tab.TabFrame;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptionPages;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import me.jellysquid.mods.sodium.client.gui.SodiumOptionsGUI;
import me.jellysquid.mods.sodium.client.gui.options.Option;
import me.jellysquid.mods.sodium.client.gui.options.OptionFlag;
import me.jellysquid.mods.sodium.client.gui.options.OptionPage;
import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage;
import me.jellysquid.mods.sodium.client.gui.utils.URLUtils;
import me.jellysquid.mods.sodium.client.gui.widgets.FlatButtonWidget;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import net.coderbot.iris.gui.screen.ShaderPackScreen;
import net.irisshaders.iris.api.v0.IrisApi;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.resources.I18n;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.input.Keyboard;
import java.io.IOException;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
public class ReeseSodiumVideoOptionsScreen extends SodiumOptionsGUI {
@Nullable
private Element focused;
private static final AtomicReference<String> tabFrameSelectedTab = new AtomicReference<>(null);
private static final AtomicReference<Integer> tabFrameScrollBarOffset = new AtomicReference<>(0);
private static final AtomicReference<Integer> optionPageScrollBarOffset = new AtomicReference<>(0);
private static final AtomicReference<String> lastSearch = new AtomicReference<>("");
private static final AtomicReference<Integer> lastSearchIndex = new AtomicReference<>(0);
private AbstractFrame frame;
private SearchTextFieldComponent searchTextField;
public ReeseSodiumVideoOptionsScreen(GuiScreen prevScreen) {
super(prevScreen);
}
// Hackalicious! Rebuild UI
@Override
public void rebuildGUI() {
this.children.clear();
this.initGui();
}
public void setFocused(@Nullable Element focused) {
this.focused = focused;
}
@Nullable
public Element getFocused() {
return this.focused;
}
@Override
public void initGui() {
this.frame = this.parentFrameBuilder().build();
this.children.add(this.frame);
this.searchTextField.setFocused(!lastSearch.get().trim().isEmpty());
if (this.searchTextField.isFocused()) {
this.setFocused(this.searchTextField);
} else {
this.setFocused(this.frame);
}
}
protected BasicFrame.Builder parentFrameBuilder() {
final BasicFrame.Builder basicFrameBuilder;
// Calculates if resolution exceeds 16:9 ratio, force 16:9
int newWidth = this.width;
if ((float) this.width / (float) this.height > 1.77777777778) {
newWidth = (int) (this.height * 1.77777777778);
}
final Dim2i basicFrameDim = new Dim2i((this.width - newWidth) / 2, 0, newWidth, this.height);
final Dim2i tabFrameDim = new Dim2i(basicFrameDim.getOriginX() + basicFrameDim.getWidth() / 20 / 2, basicFrameDim.getOriginY() + basicFrameDim.getHeight() / 4 / 2, basicFrameDim.getWidth() - (basicFrameDim.getWidth() / 20), basicFrameDim.getHeight() / 4 * 3);
final Dim2i undoButtonDim = new Dim2i(tabFrameDim.getLimitX() - 203, tabFrameDim.getLimitY() + 5, 65, 20);
final Dim2i applyButtonDim = new Dim2i(tabFrameDim.getLimitX() - 134, tabFrameDim.getLimitY() + 5, 65, 20);
final Dim2i closeButtonDim = new Dim2i(tabFrameDim.getLimitX() - 65, tabFrameDim.getLimitY() + 5, 65, 20);
final String donationText = "Buy us a coffee!";
final int donationTextWidth = this.mc.fontRenderer.getStringWidth(donationText);
final Dim2i donateButtonDim = new Dim2i(tabFrameDim.getLimitX() - 32 - donationTextWidth, tabFrameDim.getOriginY() - 26, 10 + donationTextWidth, 20);
final Dim2i hideDonateButtonDim = new Dim2i(tabFrameDim.getLimitX() - 20, tabFrameDim.getOriginY() - 26, 20, 20);
this.undoButton = new FlatButtonWidget(undoButtonDim, "Undo", this::undoChanges);
this.applyButton = new FlatButtonWidget(applyButtonDim, "Apply", this::applyChanges);
this.closeButton = new FlatButtonWidget(closeButtonDim, "Close", this::onClose);
this.donateButton = new FlatButtonWidget(donateButtonDim, donationText, this::openDonationPage);
this.hideDonateButton = new FlatButtonWidget(hideDonateButtonDim, "x", this::hideDonationButton);
if (SodiumClientMod.options().notifications.hideDonationButton) {
this.setDonationButtonVisibility(false);
}
Dim2i searchTextFieldDim;
if (SodiumClientMod.options().notifications.hideDonationButton) {
searchTextFieldDim = new Dim2i(tabFrameDim.getOriginX(), tabFrameDim.getOriginY() - 26, tabFrameDim.getWidth(), 20);
} else {
searchTextFieldDim = new Dim2i(tabFrameDim.getOriginX(), tabFrameDim.getOriginY() - 26, tabFrameDim.getWidth() - (tabFrameDim.getLimitX() - donateButtonDim.getOriginX()) - 2, 20);
}
basicFrameBuilder = this.parentBasicFrameBuilder(basicFrameDim, tabFrameDim);
if(AngelicaConfig.enableIris) {
//int size = this.client.textRenderer.getWidth(new TranslatableText(IrisApi.getInstance().getMainScreenLanguageKey()));
final String irisText = I18n.format(IrisApi.getInstance().getMainScreenLanguageKey());
final int size = this.mc.fontRenderer.getStringWidth(irisText);
final Dim2i shaderPackButtonDim;
if (!SodiumClientMod.options().notifications.hideDonationButton) {
shaderPackButtonDim = new Dim2i(donateButtonDim.getOriginX() - 12 - size, tabFrameDim.getOriginY() - 26, 10 + size, 20);
} else {
shaderPackButtonDim = new Dim2i(tabFrameDim.getLimitX() - size - 10, tabFrameDim.getOriginY() - 26, 10 + size, 20);
}
searchTextFieldDim = new Dim2i(tabFrameDim.getOriginX(), tabFrameDim.getOriginY() - 26, tabFrameDim.getWidth() - (tabFrameDim.getLimitX() - shaderPackButtonDim.getOriginX()) - 2, 20);
//FlatButtonWidget shaderPackButton = new FlatButtonWidget(shaderPackButtonDim, new TranslatableText(IrisApi.getInstance().getMainScreenLanguageKey()), () -> this.client.setScreen((Screen) IrisApi.getInstance().openMainIrisScreenObj(this)));
final FlatButtonWidget shaderPackButton = new FlatButtonWidget(shaderPackButtonDim, irisText, () -> mc.displayGuiScreen(new ShaderPackScreen(this)));
basicFrameBuilder.addChild(dim -> shaderPackButton);
}
this.searchTextField = new SearchTextFieldComponent(searchTextFieldDim, this.pages, tabFrameSelectedTab,
tabFrameScrollBarOffset, optionPageScrollBarOffset, tabFrameDim.getHeight(), this, lastSearch, lastSearchIndex);
basicFrameBuilder.addChild(dim -> this.searchTextField);
return basicFrameBuilder;
}
public BasicFrame.Builder parentBasicFrameBuilder(Dim2i parentBasicFrameDim, Dim2i tabFrameDim) {
return BasicFrame.createBuilder()
.setDimension(parentBasicFrameDim)
.shouldRenderOutline(false)
.addChild(dim -> this.donateButton)
.addChild(dim -> this.hideDonateButton)
.addChild(parentDim -> TabFrame.createBuilder()
.setDimension(tabFrameDim)
.shouldRenderOutline(false)
.setTabSectionScrollBarOffset(tabFrameScrollBarOffset)
.setTabSectionSelectedTab(tabFrameSelectedTab)
.addTabs(tabs -> this.pages
.stream()
.filter(page -> !page.getGroups().isEmpty())
.forEach(page -> tabs.add(Tab.createBuilder().from(page, optionPageScrollBarOffset)))
)
.onSetTab(() -> {
optionPageScrollBarOffset.set(0);
})
.build()
)
.addChild(dim -> this.undoButton)
.addChild(dim -> this.applyButton)
.addChild(dim -> this.closeButton);
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
super.drawDefaultBackground();
handleMouseScroll(mouseX, mouseY, partialTicks);
this.updateControls();
this.frame.render(mouseX, mouseY, partialTicks);
}
private void updateControls() {
boolean hasChanges = this.getAllOptions()
.anyMatch(Option::hasChanged);
for (OptionPage page : this.pages) {
for (Option<?> option : page.getOptions()) {
if (option.hasChanged()) {
hasChanges = true;
}
}
}
this.applyButton.setEnabled(hasChanges);
this.undoButton.setVisible(hasChanges);
this.closeButton.setEnabled(!hasChanges);
this.hasPendingChanges = hasChanges;
}
private void setDonationButtonVisibility(boolean value) {
this.donateButton.setVisible(value);
this.hideDonateButton.setVisible(value);
}
private void hideDonationButton() {
SodiumGameOptions options = SodiumClientMod.options();
options.notifications.hideDonationButton = true;
try {
options.writeChanges();
} catch (IOException e) {
throw new RuntimeException("Failed to save configuration", e);
}
this.setDonationButtonVisibility(false);
this.rebuildGUI();
}
private void openDonationPage() {
URLUtils.open("https://caffeinemc.net/donate");
}
private Stream<Option<?>> getAllOptions() {
return this.pages.stream().flatMap(s -> s.getOptions().stream());
}
private void applyChanges() {
final HashSet<OptionStorage<?>> dirtyStorages = new HashSet<>();
final EnumSet<OptionFlag> flags = EnumSet.noneOf(OptionFlag.class);
this.getAllOptions().forEach((option -> {
if (!option.hasChanged()) {
return;
}
option.applyChanges();
flags.addAll(option.getFlags());
dirtyStorages.add(option.getStorage());
}));
if (flags.contains(OptionFlag.REQUIRES_RENDERER_RELOAD)) {
this.mc.renderGlobal.loadRenderers();
}
if (flags.contains(OptionFlag.REQUIRES_ASSET_RELOAD)) {
this.mc.getTextureMapBlocks().setMipmapLevels(this.mc.gameSettings.mipmapLevels);
this.mc.refreshResources();
}
for (OptionStorage<?> storage : dirtyStorages) {
storage.save();
}
}
private void undoChanges() {
this.getAllOptions().forEach(Option::reset);
}
@Override
public void keyTyped(char typedChar, int keyCode) {
if(keyCode == Keyboard.KEY_ESCAPE && !shouldCloseOnEsc()) {
return;
} else if (keyCode == Keyboard.KEY_ESCAPE) {
onClose();
return;
}
if (keyCode == Keyboard.KEY_P) {
if(isShiftKeyDown()){
this.mc.displayGuiScreen(new GuiCustomMenu(this.prevScreen, SodiumGameOptionPages.general(), SodiumGameOptionPages.quality(), SodiumGameOptionPages.advanced(), SodiumGameOptionPages.performance()));
} else if (isCtrlKeyDown()) {
this.mc.displayGuiScreen(new SodiumOptionsGUI(this.prevScreen));
}
}
if(focused != null) {
focused.keyTyped(typedChar, keyCode);
}
}
@Override
public boolean shouldCloseOnEsc() {
return !this.hasPendingChanges;
}
@Override
public void onClose() {
lastSearch.set("");
lastSearchIndex.set(0);
super.onClose();
}
}
@@ -0,0 +1,111 @@
package me.flashyreese.mods.reeses_sodium_options.client.gui.frame;
import com.gtnewhorizons.angelica.compat.mojang.Drawable;
import com.gtnewhorizons.angelica.compat.mojang.Element;
import com.gtnewhorizons.angelica.compat.mojang.ParentElement;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import me.jellysquid.mods.sodium.client.gui.options.control.ControlElement;
import me.jellysquid.mods.sodium.client.gui.widgets.AbstractWidget;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import org.lwjgl.opengl.GL11;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractFrame extends AbstractWidget implements ParentElement {
protected final Dim2i dim;
protected final List<AbstractWidget> children = new ArrayList<>();
protected final List<Drawable> drawable = new ArrayList<>();
protected final List<ControlElement<?>> controlElements = new ArrayList<>();
protected boolean renderOutline;
private Element focused;
private boolean dragging;
public AbstractFrame(Dim2i dim, boolean renderOutline) {
this.dim = dim;
this.renderOutline = renderOutline;
}
public void buildFrame() {
for (Element element : this.children) {
if (element instanceof AbstractFrame abstractFrame) {
this.controlElements.addAll(abstractFrame.controlElements);
}
if (element instanceof ControlElement<?> controlElement) {
this.controlElements.add(controlElement);
}
if (element instanceof Drawable drawable) {
this.drawable.add(drawable);
}
}
}
@Override
public void render(int mouseX, int mouseY, float delta) {
if (this.renderOutline) {
this.drawRectOutline(this.dim.getOriginX(), this.dim.getOriginY(), this.dim.getLimitX(), this.dim.getLimitY(), 0xFFAAAAAA);
}
for (Drawable drawable : this.drawable) {
drawable.render(mouseX, mouseY, delta);
}
}
public void applyScissor(int x, int y, int width, int height, Runnable action) {
final double scale = new ScaledResolution(Minecraft.getMinecraft(), Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight).getScaleFactor();
GLStateManager.enableScissorTest();
GL11.glScissor((int) (x * scale), (int) (Minecraft.getMinecraft().getFramebuffer().framebufferHeight - (y + height) * scale), (int) (width * scale), (int) (height * scale));
action.run();
GLStateManager.disableScissorTest();
}
protected void drawRectOutline(double x, double y, double w, double h, int color) {
final float a = (float) (color >> 24 & 255) / 255.0F;
final float r = (float) (color >> 16 & 255) / 255.0F;
final float g = (float) (color >> 8 & 255) / 255.0F;
final float b = (float) (color & 255) / 255.0F;
this.drawQuads(vertices -> {
addQuad(vertices, x, y, w, y + 1, a, r, g, b);
addQuad(vertices, x, h - 1, w, h, a, r, g, b);
addQuad(vertices, x, y, x + 1, h, a, r, g, b);
addQuad(vertices, w - 1, y, w, h, a, r, g, b);
});
}
@Override
public boolean isDragging() {
return this.dragging;
}
@Override
public void setDragging(boolean dragging) {
this.dragging = dragging;
}
@Nullable
@Override
public Element getFocused() {
return this.focused;
}
@Override
public void setFocused(@Nullable Element focused) {
this.focused = focused;
}
@Override
public List<? extends Element> children() {
return this.children;
}
@Override
public boolean isMouseOver(double mouseX, double mouseY) {
return this.dim.containsCursor(mouseX, mouseY);
}
}
@@ -0,0 +1,67 @@
package me.flashyreese.mods.reeses_sodium_options.client.gui.frame;
import me.jellysquid.mods.sodium.client.gui.widgets.AbstractWidget;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import org.apache.commons.lang3.Validate;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class BasicFrame extends AbstractFrame {
protected List<Function<Dim2i, AbstractWidget>> functions;
public BasicFrame(Dim2i dim, boolean renderOutline, List<Function<Dim2i, AbstractWidget>> functions) {
super(dim, renderOutline);
this.functions = functions;
this.buildFrame();
}
public static Builder createBuilder() {
return new Builder();
}
@Override
public void buildFrame() {
this.children.clear();
this.drawable.clear();
this.controlElements.clear();
this.functions.forEach(function -> this.children.add(function.apply(dim)));
super.buildFrame();
}
@Override
public void render(int mouseX, int mouseY, float delta) {
super.render(mouseX, mouseY, delta);
}
public static class Builder {
private final List<Function<Dim2i, AbstractWidget>> functions = new ArrayList<>();
private Dim2i dim;
private boolean renderOutline;
public Builder setDimension(Dim2i dim) {
this.dim = dim;
return this;
}
public Builder shouldRenderOutline(boolean renderOutline) {
this.renderOutline = renderOutline;
return this;
}
public Builder addChild(Function<Dim2i, AbstractWidget> function) {
this.functions.add(function);
return this;
}
public BasicFrame build() {
Validate.notNull(this.dim, "Dimension must be specified");
return new BasicFrame(this.dim, this.renderOutline, this.functions);
}
}
}
@@ -0,0 +1,186 @@
package me.flashyreese.mods.reeses_sodium_options.client.gui.frame;
import me.flashyreese.mods.reeses_sodium_options.client.gui.OptionExtended;
import me.jellysquid.mods.sodium.client.gui.options.Option;
import me.jellysquid.mods.sodium.client.gui.options.OptionGroup;
import me.jellysquid.mods.sodium.client.gui.options.OptionImpact;
import me.jellysquid.mods.sodium.client.gui.options.OptionPage;
import me.jellysquid.mods.sodium.client.gui.options.control.Control;
import me.jellysquid.mods.sodium.client.gui.options.control.ControlElement;
import me.jellysquid.mods.sodium.client.gui.options.control.element.SodiumControlElementFactory;
import me.jellysquid.mods.sodium.client.gui.widgets.AbstractWidget;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.EnumChatFormatting;
import org.apache.commons.lang3.Validate;
import java.util.ArrayList;
import java.util.List;
public class OptionPageFrame extends AbstractFrame {
protected static final SodiumControlElementFactory elementFactory = new SodiumControlElementFactory();
protected final Dim2i originalDim;
protected final OptionPage page;
private long lastTime = 0;
private ControlElement<?> lastHoveredElement = null;
public OptionPageFrame(Dim2i dim, boolean renderOutline, OptionPage page) {
super(dim, renderOutline);
this.originalDim = new Dim2i(dim.getOriginX(), dim.getOriginY(), dim.getWidth(), dim.getHeight());
this.page = page;
this.setupFrame();
this.buildFrame();
}
public static Builder createBuilder() {
return new Builder();
}
public void setupFrame() {
this.children.clear();
this.drawable.clear();
this.controlElements.clear();
int y = 0;
if (!this.page.getGroups().isEmpty()) {
OptionGroup lastGroup = this.page.getGroups().get(this.page.getGroups().size() - 1);
for (OptionGroup group : this.page.getGroups()) {
y += group.getOptions().size() * 18;
if (group != lastGroup) {
y += 4;
}
}
}
this.dim.setHeight(y);
this.page.getGroups().forEach(group -> group.getOptions().forEach(option -> {
if (option instanceof OptionExtended<?> optionExtended) {
optionExtended.setParentDimension(this.dim);
}
}));
}
@Override
public void buildFrame() {
if (this.page == null) return;
this.children.clear();
this.drawable.clear();
this.controlElements.clear();
int y = 0;
for (OptionGroup group : this.page.getGroups()) {
// Add each option's control element
for (Option<?> option : group.getOptions()) {
final Control<?> control = option.getControl();
final ControlElement<?> element = control.createElement(new Dim2i(this.dim.getOriginX(), this.dim.getOriginY() + y, this.dim.getWidth(), 18), elementFactory);
// This is probably not safe
this.children.add((AbstractWidget) element);
// Move down to the next option
y += 18;
}
// Add padding beneath each option group
y += 4;
}
super.buildFrame();
}
@Override
public void render(int mouseX, int mouseY, float delta) {
final ControlElement<?> hoveredElement = this.controlElements.stream()
.filter(controlElement -> controlElement.getDimensions().overlapWith(this.originalDim))
.filter(ControlElement::isHovered)
.findFirst()
.orElse(null);
super.render(mouseX, mouseY, delta);
if (hoveredElement != null && this.lastHoveredElement == hoveredElement &&
(this.originalDim.containsCursor(mouseX, mouseY) && hoveredElement.isHovered()/* && isMouseOver(mouseX, mouseY)*/)) {
if (this.lastTime == 0) {
this.lastTime = System.currentTimeMillis();
}
this.renderOptionTooltip(hoveredElement);
} else {
this.lastTime = 0;
this.lastHoveredElement = hoveredElement;
}
}
private void renderOptionTooltip(ControlElement<?> element) {
final FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer;
if (this.lastTime + 500 > System.currentTimeMillis()) return;
final Dim2i dim = element.getDimensions();
final int textPadding = 3;
final int boxPadding = 3;
final int boxWidth = dim.getWidth();
//Offset based on mouse position, width and height of content and width and height of the window
int boxY = dim.getLimitY();
final int boxX = dim.getOriginX();
final Option<?> option = element.getOption();
final List<String> tooltip = new ArrayList<>(fontRenderer.listFormattedStringToWidth(option.getTooltip(), boxWidth - (textPadding * 2)));
final OptionImpact impact = option.getImpact();
if (impact != null) {
tooltip.add(EnumChatFormatting.GRAY + I18n.format("sodium.options.performance_impact_string", impact.toDisplayString()));
}
final int boxHeight = (tooltip.size() * 12) + boxPadding;
final int boxYLimit = boxY + boxHeight;
final int boxYCutoff = this.originalDim.getLimitY();
// If the box is going to be cutoff on the Y-axis, move it back up the difference
if (boxYLimit > boxYCutoff) {
boxY -= boxHeight + dim.getHeight();
}
if (boxY < 0) {
boxY = dim.getLimitY();
}
this.drawRect(boxX, boxY, boxX + boxWidth, boxY + boxHeight, 0xE0000000);
this.drawRectOutline(boxX, boxY, boxX + boxWidth, boxY + boxHeight, 0xFF94E4D3);
for (int i = 0; i < tooltip.size(); i++) {
fontRenderer.drawString(tooltip.get(i), boxX + textPadding, boxY + textPadding + (i * 12), 0xFFFFFFFF);
}
}
public static class Builder {
private Dim2i dim;
private boolean renderOutline;
private OptionPage page;
public Builder setDimension(Dim2i dim) {
this.dim = dim;
return this;
}
public Builder shouldRenderOutline(boolean renderOutline) {
this.renderOutline = renderOutline;
return this;
}
public Builder setOptionPage(OptionPage page) {
this.page = page;
return this;
}
public OptionPageFrame build() {
Validate.notNull(this.dim, "Dimension must be specified");
Validate.notNull(this.page, "Option Page must be specified");
return new OptionPageFrame(this.dim, this.renderOutline, this.page);
}
}
}
@@ -0,0 +1,185 @@
package me.flashyreese.mods.reeses_sodium_options.client.gui.frame;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.components.ScrollBarComponent;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import java.util.concurrent.atomic.AtomicReference;
public class ScrollableFrame extends AbstractFrame {
protected final Dim2i frameOrigin;
protected final AbstractFrame frame;
private boolean canScrollHorizontal;
private boolean canScrollVertical;
private Dim2i viewPortDimension = null;
private ScrollBarComponent verticalScrollBar = null;
private ScrollBarComponent horizontalScrollBar = null;
public ScrollableFrame(Dim2i dim, AbstractFrame frame, boolean renderOutline, AtomicReference<Integer> verticalScrollBarOffset, AtomicReference<Integer> horizontalScrollBarOffset) {
super(dim, renderOutline);
this.frame = frame;
this.frameOrigin = new Dim2i(frame.dim.getOriginX(), frame.dim.getOriginY(), 0, 0);
this.setupFrame(verticalScrollBarOffset, horizontalScrollBarOffset);
this.buildFrame();
}
public static Builder createBuilder() {
return new Builder();
}
public void setupFrame(AtomicReference<Integer> verticalScrollBarOffset, AtomicReference<Integer> horizontalScrollBarOffset) {
int maxWidth = 0;
int maxHeight = 0;
if (!this.dim.canFitDimension(this.frame.dim)) {
if (this.dim.getLimitX() < this.frame.dim.getLimitX()) {
int value = this.frame.dim.getOriginX() - this.dim.getOriginX() + this.frame.dim.getWidth();
if (maxWidth < value) {
maxWidth = value;
}
}
if (this.dim.getLimitY() < this.frame.dim.getLimitY()) {
int value = this.frame.dim.getOriginY() - this.dim.getOriginY() + this.frame.dim.getHeight();
if (maxHeight < value) {
maxHeight = value;
}
}
}
if (maxWidth > 0) {
this.canScrollHorizontal = true;
}
if (maxHeight > 0) {
this.canScrollVertical = true;
}
if (this.canScrollHorizontal && this.canScrollVertical) {
this.viewPortDimension = new Dim2i(this.dim.getOriginX(), this.dim.getOriginY(), this.dim.getWidth() - 11, this.dim.getHeight() - 11);
} else if (this.canScrollHorizontal) {
this.viewPortDimension = new Dim2i(this.dim.getOriginX(), this.dim.getOriginY(), this.dim.getWidth(), this.dim.getHeight() - 11);
this.frame.dim.setHeight(this.frame.dim.getHeight() - 11); // fixme: don't mutate rather
} else if (this.canScrollVertical) {
this.viewPortDimension = new Dim2i(this.dim.getOriginX(), this.dim.getOriginY(), this.dim.getWidth() - 11, this.dim.getHeight());
this.frame.dim.setWidth(this.frame.dim.getWidth() - 11); // fixme: don't mutate rather
}
if (this.canScrollHorizontal) {
this.horizontalScrollBar = new ScrollBarComponent(new Dim2i(this.viewPortDimension.getOriginX(), this.viewPortDimension.getLimitY() + 1, this.viewPortDimension.getWidth(), 10), ScrollBarComponent.Mode.HORIZONTAL, this.frame.dim.getWidth(), this.viewPortDimension.getWidth(), offset -> {
this.buildFrame();
horizontalScrollBarOffset.set(offset);
});
this.horizontalScrollBar.setOffset(horizontalScrollBarOffset.get());
}
if (this.canScrollVertical) {
this.verticalScrollBar = new ScrollBarComponent(new Dim2i(this.viewPortDimension.getLimitX() + 1, this.viewPortDimension.getOriginY(), 10, this.viewPortDimension.getHeight()), ScrollBarComponent.Mode.VERTICAL, this.frame.dim.getHeight(), this.viewPortDimension.getHeight(), offset -> {
this.buildFrame();
verticalScrollBarOffset.set(offset);
}, this.viewPortDimension);
this.verticalScrollBar.setOffset(verticalScrollBarOffset.get());
}
}
@Override
public void buildFrame() {
this.children.clear();
this.drawable.clear();
this.controlElements.clear();
if (this.canScrollHorizontal) {
this.horizontalScrollBar.updateThumbPosition();
}
if (this.canScrollVertical) {
this.verticalScrollBar.updateThumbPosition();
}
if (this.canScrollHorizontal) {
this.frame.dim.setX(this.frameOrigin.getOriginX() - this.horizontalScrollBar.getOffset());
}
if (this.canScrollVertical) {
this.frame.dim.setY(this.frameOrigin.getOriginY() - this.verticalScrollBar.getOffset());
}
this.frame.buildFrame();
this.children.add(this.frame);
super.buildFrame();
}
@Override
public void render(int mouseX, int mouseY, float delta) {
if (this.canScrollHorizontal || this.canScrollVertical) {
if (this.renderOutline) {
this.drawRectOutline(this.dim.getOriginX(), this.dim.getOriginY(), this.dim.getLimitX(), this.dim.getLimitY(), 0xFFAAAAAA);
}
this.applyScissor(this.viewPortDimension.getOriginX(), this.viewPortDimension.getOriginY(), this.viewPortDimension.getWidth(), this.viewPortDimension.getHeight(), () -> super.render(mouseX, mouseY, delta));
} else {
super.render(mouseX, mouseY, delta);
}
if (this.canScrollHorizontal) {
this.horizontalScrollBar.render(mouseX, mouseY, delta);
}
if (this.canScrollVertical) {
this.verticalScrollBar.render(mouseX, mouseY, delta);
}
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
return super.mouseClicked(mouseX, mouseY, button) || (this.canScrollHorizontal && this.horizontalScrollBar.mouseClicked(mouseX, mouseY, button)) || (this.canScrollVertical && this.verticalScrollBar.mouseClicked(mouseX, mouseY, button));
}
@Override
public boolean mouseDragged(double mouseX, double mouseY, int button) {
return super.mouseDragged(mouseX, mouseY, button) || (this.canScrollHorizontal && this.horizontalScrollBar.mouseDragged(mouseX, mouseY, button)) || (this.canScrollVertical && this.verticalScrollBar.mouseDragged(mouseX, mouseY, button));
}
@Override
public boolean mouseReleased(double mouseX, double mouseY, int button) {
return super.mouseReleased(mouseX, mouseY, button) || (this.canScrollHorizontal && this.horizontalScrollBar.mouseReleased(mouseX, mouseY, button)) || (this.canScrollVertical && this.verticalScrollBar.mouseReleased(mouseX, mouseY, button));
}
@Override
public boolean mouseScrolled(double mouseX, double mouseY, double amount) {
return super.mouseScrolled(mouseX, mouseY, amount) || (this.canScrollHorizontal && this.horizontalScrollBar.mouseScrolled(mouseX, mouseY, amount)) || (this.canScrollVertical && this.verticalScrollBar.mouseScrolled(mouseX, mouseY, amount));
}
public static class Builder {
private boolean renderOutline = false;
private Dim2i dim = null;
private AbstractFrame frame = null;
private AtomicReference<Integer> verticalScrollBarOffset = new AtomicReference<>(0);
private AtomicReference<Integer> horizontalScrollBarOffset = new AtomicReference<>(0);
public Builder setDimension(Dim2i dim) {
this.dim = dim;
return this;
}
public Builder shouldRenderOutline(boolean state) {
this.renderOutline = state;
return this;
}
public Builder setVerticalScrollBarOffset(AtomicReference<Integer> verticalScrollBarOffset) {
this.verticalScrollBarOffset = verticalScrollBarOffset;
return this;
}
public Builder setHorizontalScrollBarOffset(AtomicReference<Integer> horizontalScrollBarOffset) {
this.horizontalScrollBarOffset = horizontalScrollBarOffset;
return this;
}
public Builder setFrame(AbstractFrame frame) {
this.frame = frame;
return this;
}
public ScrollableFrame build() {
return new ScrollableFrame(this.dim, this.frame, this.renderOutline, this.verticalScrollBarOffset, this.horizontalScrollBarOffset);
}
}
}
@@ -0,0 +1,143 @@
package me.flashyreese.mods.reeses_sodium_options.client.gui.frame.components;
import lombok.Getter;
import me.jellysquid.mods.sodium.client.gui.widgets.AbstractWidget;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import net.minecraft.util.MathHelper;
import java.util.function.Consumer;
public class ScrollBarComponent extends AbstractWidget {
protected static final int SCROLL_OFFSET = 6;
protected final Dim2i dim;
private final Mode mode;
private final int frameLength;
private final int viewPortLength;
private final int maxScrollBarOffset;
private final Consumer<Integer> onSetOffset;
@Getter
private int offset = 0;
private boolean isDragging;
private Dim2i scrollThumb = null;
private int scrollThumbClickOffset;
private Dim2i extendedScrollArea = null;
public ScrollBarComponent(Dim2i trackArea, Mode mode, int frameLength, int viewPortLength, Consumer<Integer> onSetOffset) {
this.dim = trackArea;
this.mode = mode;
this.frameLength = frameLength;
this.viewPortLength = viewPortLength;
this.onSetOffset = onSetOffset;
this.maxScrollBarOffset = this.frameLength - this.viewPortLength;
}
public ScrollBarComponent(Dim2i scrollBarArea, Mode mode, int frameLength, int viewPortLength, Consumer<Integer> onSetOffset, Dim2i extendedTrackArea) {
this(scrollBarArea, mode, frameLength, viewPortLength, onSetOffset);
this.extendedScrollArea = extendedTrackArea;
}
public void updateThumbPosition() {
int scrollThumbLength = (this.viewPortLength * (this.mode == Mode.VERTICAL ? this.dim.getHeight() : this.dim.getWidth() - 6)) / this.frameLength;
int maximumScrollThumbOffset = this.viewPortLength - scrollThumbLength;
int scrollThumbOffset = this.offset * maximumScrollThumbOffset / this.maxScrollBarOffset;
this.scrollThumb = new Dim2i(this.dim.getOriginX() + 2 + (this.mode == Mode.HORIZONTAL ? scrollThumbOffset : 0), this.dim.getOriginY() + 2 + (this.mode == Mode.VERTICAL ? scrollThumbOffset : 0), (this.mode == Mode.VERTICAL ? this.dim.getWidth() : scrollThumbLength) - 4, (this.mode == Mode.VERTICAL ? scrollThumbLength : this.dim.getHeight()) - 4);
}
@Override
public void render(int mouseX, int mouseY, float delta) {
this.drawRectOutline(this.dim.getOriginX(), this.dim.getOriginY(), this.dim.getLimitX(), this.dim.getLimitY(), 0xFFAAAAAA);
this.drawRect(this.scrollThumb.getOriginX(), this.scrollThumb.getOriginY(), this.scrollThumb.getLimitX(), this.scrollThumb.getLimitY(), 0xFFAAAAAA);
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (this.dim.containsCursor(mouseX, mouseY)) {
if (this.scrollThumb.containsCursor(mouseX, mouseY)) {
if (this.mode == Mode.VERTICAL) {
this.scrollThumbClickOffset = (int) (mouseY - this.scrollThumb.getCenterY());
} else {
this.scrollThumbClickOffset = (int) (mouseX - this.scrollThumb.getCenterX());
}
this.isDragging = true;
} else {
int value;
if (this.mode == Mode.VERTICAL) {
value = (int) ((mouseY - this.dim.getOriginY() - (this.scrollThumb.getHeight() / 2)) / (this.dim.getHeight() - this.scrollThumb.getHeight()) * this.maxScrollBarOffset);
} else {
value = (int) ((mouseX - this.dim.getOriginX() - (this.scrollThumb.getWidth() / 2)) / (this.dim.getWidth() - this.scrollThumb.getWidth()) * this.maxScrollBarOffset);
}
this.setOffset(value);
this.isDragging = false;
}
return true;
}
this.isDragging = false;
return false;
}
@Override
public boolean mouseReleased(double mouseX, double mouseY, int button) {
if (button == 0) {
this.isDragging = false;
}
return false;
}
@Override
public boolean mouseDragged(double mouseX, double mouseY, int button) {
if (this.isDragging) {
final int value;
if (this.mode == Mode.VERTICAL) {
value = (int) ((mouseY - this.scrollThumbClickOffset - this.dim.getOriginY() - (this.scrollThumb.getHeight() / 2)) / (this.dim.getHeight() - this.scrollThumb.getHeight()) * this.maxScrollBarOffset);
} else {
value = (int) ((mouseX - this.scrollThumbClickOffset - this.dim.getOriginX() - (this.scrollThumb.getWidth() / 2)) / (this.dim.getWidth() - this.scrollThumb.getWidth()) * this.maxScrollBarOffset);
}
this.setOffset(value);
return true;
}
return false;
}
@Override
public boolean mouseScrolled(double mouseX, double mouseY, double amount) {
if (this.dim.containsCursor(mouseX, mouseY) || this.extendedScrollArea != null && this.extendedScrollArea.containsCursor(mouseX, mouseY)) {
if (this.offset <= this.maxScrollBarOffset && this.offset >= 0) {
int value = (int) (this.offset - amount * SCROLL_OFFSET);
this.setOffset(value);
return true;
}
}
return false;
}
public void setOffset(int value) {
this.offset = MathHelper.clamp_int(value, 0, this.maxScrollBarOffset);
this.updateThumbPosition();
this.onSetOffset.accept(this.offset);
}
protected void drawRectOutline(double x, double y, double w, double h, int color) {
final float a = (float) (color >> 24 & 255) / 255.0F;
final float r = (float) (color >> 16 & 255) / 255.0F;
final float g = (float) (color >> 8 & 255) / 255.0F;
final float b = (float) (color & 255) / 255.0F;
this.drawQuads(vertices -> {
addQuad(vertices, x, y, w, y + 1, a, r, g, b);
addQuad(vertices, x, h - 1, w, h, a, r, g, b);
addQuad(vertices, x, y, x + 1, h, a, r, g, b);
addQuad(vertices, w - 1, y, w, h, a, r, g, b);
});
}
public enum Mode {
HORIZONTAL,
VERTICAL
}
}
@@ -0,0 +1,499 @@
package me.flashyreese.mods.reeses_sodium_options.client.gui.frame.components;
import lombok.Getter;
import lombok.Setter;
import me.flashyreese.mods.reeses_sodium_options.client.gui.OptionExtended;
import me.flashyreese.mods.reeses_sodium_options.client.gui.ReeseSodiumVideoOptionsScreen;
import me.flashyreese.mods.reeses_sodium_options.util.StringUtils;
import me.jellysquid.mods.sodium.client.gui.options.Option;
import me.jellysquid.mods.sodium.client.gui.options.OptionPage;
import me.jellysquid.mods.sodium.client.gui.widgets.AbstractWidget;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.ChatAllowedCharacters;
import net.minecraft.util.MathHelper;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
public class SearchTextFieldComponent extends AbstractWidget {
protected final Dim2i dim;
protected final List<OptionPage> pages;
private final FontRenderer textRenderer = Minecraft.getMinecraft().fontRenderer;
private final Predicate<String> textPredicate = Objects::nonNull;
private final AtomicReference<String> tabFrameSelectedTab;
private final AtomicReference<Integer> tabFrameScrollBarOffset;
private final AtomicReference<Integer> optionPageScrollBarOffset;
private final int tabDimHeight;
private final ReeseSodiumVideoOptionsScreen sodiumVideoOptionsScreen;
private final AtomicReference<String> lastSearch;
private final AtomicReference<Integer> lastSearchIndex;
protected boolean selecting;
protected String text = "";
protected int maxLength = 100;
@Getter
protected boolean visible = true;
@Getter
protected boolean editable = true;
private int firstCharacterIndex;
private int selectionStart;
private int selectionEnd;
@Setter
@Getter
private boolean focused;
private int lastCursorPosition = this.getCursor();
public SearchTextFieldComponent(Dim2i dim, List<OptionPage> pages, AtomicReference<String> tabFrameSelectedTab, AtomicReference<Integer> tabFrameScrollBarOffset, AtomicReference<Integer> optionPageScrollBarOffset, int tabDimHeight, ReeseSodiumVideoOptionsScreen sodiumVideoOptionsScreen, AtomicReference<String> lastSearch, AtomicReference<Integer> lastSearchIndex) {
this.dim = dim;
this.pages = pages;
this.tabFrameSelectedTab = tabFrameSelectedTab;
this.tabFrameScrollBarOffset = tabFrameScrollBarOffset;
this.optionPageScrollBarOffset = optionPageScrollBarOffset;
this.tabDimHeight = tabDimHeight;
this.sodiumVideoOptionsScreen = sodiumVideoOptionsScreen;
this.lastSearch = lastSearch;
this.lastSearchIndex = lastSearchIndex;
if (!lastSearch.get().trim().isEmpty()) {
this.write(lastSearch.get());
}
}
@Override
public void render(int mouseX, int mouseY, float delta) {
if (!this.isVisible()) {
return;
}
if (!this.isFocused() && this.text.isEmpty()) {
final String key = "rso.search_bar_empty";
String text = I18n.format(key);
if (text.equals(key))
text = "Search options...";
this.textRenderer.drawString(text, this.dim.getOriginX() + 6, this.dim.getOriginY() + 6, 0xFFAAAAAA);
}
drawRect(this.dim.getOriginX(), this.dim.getOriginY(), this.dim.getLimitX(), this.dim.getLimitY(), this.isFocused() ? 0xE0000000 : 0x90000000);
final int j = this.selectionStart - this.firstCharacterIndex;
int k = this.selectionEnd - this.firstCharacterIndex;
final String string = this.textRenderer.trimStringToWidth(this.text.substring(this.firstCharacterIndex), this.getInnerWidth());
final boolean bl = j >= 0 && j <= string.length();
final int l = this.dim.getOriginX() + 6;
final int m = this.dim.getOriginY() + 6;
int n = l;
if (k > string.length()) {
k = string.length();
}
if (!string.isEmpty()) {
final String string2 = bl ? string.substring(0, j) : string;
n = this.textRenderer.drawStringWithShadow(string2, n, m, 0xE0E0E0);
}
final boolean bl3 = this.selectionStart < this.text.length() || this.text.length() >= this.getMaxLength();
int o = n;
if (!bl) {
o = j > 0 ? l + this.dim.getWidth() - 12 : l;
} else if (bl3) {
--o;
--n;
}
if (!string.isEmpty() && bl && j < string.length()) {
this.textRenderer.drawStringWithShadow(string.substring(j), n, m, 0xE0E0E0);
}
// Cursor
if (this.isFocused()) {
drawRect(o, m - 1, o + 1, m + 1 + this.textRenderer.FONT_HEIGHT, -0x2F2F30);
}
// Highlighted text
if (k != j) {
final int p = l + this.textRenderer.getStringWidth(string.substring(0, k));
this.drawSelectionHighlight(o, m - 1, p - 1, m + 1 + this.textRenderer.FONT_HEIGHT);
}
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
final int i = MathHelper.floor_double(mouseX) - this.dim.getOriginX() - 6;
final String string = this.textRenderer.trimStringToWidth(this.text.substring(this.firstCharacterIndex), this.getInnerWidth());
this.setCursor(this.textRenderer.trimStringToWidth(string, i).length() + this.firstCharacterIndex);
this.setFocused(this.dim.containsCursor(mouseX, mouseY));
this.pages.forEach(page -> page
.getOptions()
.stream()
.filter(OptionExtended.class::isInstance)
.map(OptionExtended.class::cast)
.forEach(optionExtended -> optionExtended.setSelected(false)));
return this.isFocused();
}
private void drawSelectionHighlight(int x1, int y1, int x2, int y2) {
int i;
if (x1 < x2) {
i = x1;
x1 = x2;
x2 = i;
}
if (y1 < y2) {
i = y1;
y1 = y2;
y2 = i;
}
if (x2 > this.dim.getOriginX() + this.dim.getWidth()) {
x2 = this.dim.getOriginX() + this.dim.getWidth();
}
if (x1 > this.dim.getOriginX() + this.dim.getWidth()) {
x1 = this.dim.getOriginX() + this.dim.getWidth();
}
GL11.glEnable(GL11.GL_COLOR_LOGIC_OP);
GL11.glLogicOp(GL11.GL_OR_REVERSE);
drawRect(x1, y1, x2, y2, -0xFFFF01);
GL11.glDisable(GL11.GL_COLOR_LOGIC_OP);
}
private int getMaxLength() {
return this.maxLength;
}
public String getSelectedText() {
final int i = Math.min(this.selectionStart, this.selectionEnd);
final int j = Math.max(this.selectionStart, this.selectionEnd);
return this.text.substring(i, j);
}
public void write(String text) {
final int i = Math.min(this.selectionStart, this.selectionEnd);
final int j = Math.max(this.selectionStart, this.selectionEnd);
final int k = this.maxLength - this.text.length() - (i - j);
String string = text; //SharedConstants.stripInvalidChars(text);
int l = string.length();
if (k < l) {
string = string.substring(0, k);
l = k;
}
final String string2 = (new StringBuilder(this.text)).replace(i, j, string).toString();
if (this.textPredicate.test(string2)) {
this.text = string2;
this.setSelectionStart(i + l);
this.setSelectionEnd(this.selectionStart);
this.onChanged(this.text);
}
}
private void onChanged(String newText) {
this.pages.forEach(page -> page
.getOptions()
.stream()
.filter(OptionExtended.class::isInstance)
.map(OptionExtended.class::cast)
.forEach(optionExtended -> optionExtended.setHighlight(false)));
this.lastSearch.set(newText.trim());
if (this.editable && (!newText.trim().isEmpty())) {
final List<Option<?>> fuzzy = StringUtils.fuzzySearch(this.pages, newText, 2);
fuzzy.stream()
.filter(OptionExtended.class::isInstance)
.map(OptionExtended.class::cast)
.forEach(optionExtended -> optionExtended.setHighlight(true));
}
}
private void erase(int offset) {
if (GuiScreen.isCtrlKeyDown()) {
this.eraseWords(offset);
} else {
this.eraseCharacters(offset);
}
}
public void eraseWords(int wordOffset) {
if (!this.text.isEmpty()) {
if (this.selectionEnd != this.selectionStart) {
this.write("");
} else {
this.eraseCharacters(this.getWordSkipPosition(wordOffset) - this.selectionStart);
}
}
}
public void eraseCharacters(int characterOffset) {
if (!this.text.isEmpty()) {
if (this.selectionEnd != this.selectionStart) {
this.write("");
} else {
final int i = this.getCursorPosWithOffset(characterOffset);
final int j = Math.min(i, this.selectionStart);
final int k = Math.max(i, this.selectionStart);
if (j != k) {
final String string = (new StringBuilder(this.text)).delete(j, k).toString();
if (this.textPredicate.test(string)) {
this.text = string;
this.setCursor(j);
this.onChanged(this.text);
}
}
}
}
}
public int getWordSkipPosition(int wordOffset) {
return this.getWordSkipPosition(wordOffset, this.getCursor());
}
private int getWordSkipPosition(int wordOffset, int cursorPosition) {
return this.getWordSkipPosition(wordOffset, cursorPosition, true);
}
private int getWordSkipPosition(int wordOffset, int cursorPosition, boolean skipOverSpaces) {
int i = cursorPosition;
final boolean bl = wordOffset < 0;
final int j = Math.abs(wordOffset);
for (int k = 0; k < j; ++k) {
if (!bl) {
final int l = this.text.length();
i = this.text.indexOf(32, i);
if (i == -1) {
i = l;
} else {
while (skipOverSpaces && i < l && this.text.charAt(i) == ' ') {
++i;
}
}
} else {
while (skipOverSpaces && i > 0 && this.text.charAt(i - 1) == ' ') {
--i;
}
while (i > 0 && this.text.charAt(i - 1) != ' ') {
--i;
}
}
}
return i;
}
public int getCursor() {
return this.selectionStart;
}
public void setCursor(int cursor) {
this.setSelectionStart(cursor);
if (!this.selecting) {
this.setSelectionEnd(this.selectionStart);
}
this.onChanged(this.text);
}
public void moveCursor(int offset) {
this.setCursor(this.getCursorPosWithOffset(offset));
}
private int getCursorPosWithOffset(int offset) {
//return Util.moveCursor(this.text, this.selectionStart, offset);
return this.selectionStart + offset;
}
public void setSelectionStart(int cursor) {
this.selectionStart = MathHelper.clamp_int(cursor, 0, this.text.length());
}
public void setCursorToStart() {
this.setCursor(0);
}
public void setCursorToEnd() {
this.setCursor(this.text.length());
}
public void setSelectionEnd(int index) {
final int i = this.text.length();
this.selectionEnd = MathHelper.clamp_int(index, 0, i);
if (this.textRenderer != null) {
if (this.firstCharacterIndex > i) {
this.firstCharacterIndex = i;
}
final int j = this.getInnerWidth();
final String string = this.textRenderer.trimStringToWidth(this.text.substring(this.firstCharacterIndex), j);
final int k = string.length() + this.firstCharacterIndex;
if (this.selectionEnd == this.firstCharacterIndex) {
this.firstCharacterIndex -= this.textRenderer.trimStringToWidth(this.text, j, true).length();
}
if (this.selectionEnd > k) {
this.firstCharacterIndex += this.selectionEnd - k;
} else if (this.selectionEnd <= this.firstCharacterIndex) {
this.firstCharacterIndex -= this.firstCharacterIndex - this.selectionEnd;
}
this.firstCharacterIndex = MathHelper.clamp_int(this.firstCharacterIndex, 0, i);
}
}
public boolean isActive() {
return this.isVisible() && this.isFocused() && this.isEditable();
}
// @Override
// public boolean charTyped(char chr, int modifiers) {
// if (!this.isActive()) {
// return false;
// }
// if (SharedConstants.isValidChar(chr)) {
// if (this.editable) {
// this.lastSearch.set(this.text.trim());
// this.write(Character.toString(chr));
// this.lastSearchIndex.set(0);
// }
// return true;
// }
// return false;
// }
//
@Override
public boolean keyTyped(char typedChar, int keyCode) {
this.pages.forEach(page2 -> page2
.getOptions()
.stream()
.filter(OptionExtended.class::isInstance)
.map(OptionExtended.class::cast)
.forEach(optionExtended2 -> optionExtended2.setSelected(false)));
if (!this.isActive()) {
return false;
} else {
this.selecting = GuiScreen.isShiftKeyDown();
if (keyCode == Keyboard.KEY_A && GuiScreen.isCtrlKeyDown() && !GuiScreen.isShiftKeyDown() ) {
// Select all
this.setCursorToEnd();
this.setSelectionEnd(0);
return true;
} else if (keyCode == Keyboard.KEY_C && GuiScreen.isCtrlKeyDown() && !GuiScreen.isShiftKeyDown() ) {
// Copy
GuiScreen.setClipboardString(this.getSelectedText());
return true;
} else if (keyCode == Keyboard.KEY_V && GuiScreen.isCtrlKeyDown() && !GuiScreen.isShiftKeyDown() ) {
// Paste
if (this.editable) {
this.write(GuiScreen.getClipboardString());
}
return true;
} else if (keyCode == Keyboard.KEY_X && GuiScreen.isCtrlKeyDown() && !GuiScreen.isShiftKeyDown() ) {
// Cut
GuiScreen.setClipboardString(this.getSelectedText());
if (this.editable) {
this.write("");
}
return true;
} else {
switch (keyCode) {
case Keyboard.KEY_RETURN: // GLFW.GLFW_KEY_ENTER
if (this.editable) {
int count = 0;
for (OptionPage page : this.pages) {
for (Option<?> option : page.getOptions()) {
if(option instanceof OptionExtended<?> optionExtended) {
if (optionExtended.isHighlight() && optionExtended.getParentDimension() != null) {
if (count == this.lastSearchIndex.get()) {
final Dim2i optionDim = optionExtended.getDim2i();
final Dim2i parentDim = optionExtended.getParentDimension();
final int maxOffset = parentDim.getHeight() - this.tabDimHeight;
final int input = optionDim.getOriginY() - parentDim.getOriginY();
final int inputOffset = input + optionDim.getHeight() == parentDim.getHeight() ? parentDim.getHeight() : input;
final int offset = inputOffset * maxOffset / parentDim.getHeight();
int total = this.pages.stream().mapToInt(page2 -> Math.toIntExact(page2.getOptions().stream().filter(OptionExtended.class::isInstance).map(OptionExtended.class::cast).filter(OptionExtended::isHighlight).count())).sum();
final int value = total == this.lastSearchIndex.get() + 1 ? 0 : this.lastSearchIndex.get() + 1;
optionExtended.setSelected(true);
this.lastSearchIndex.set(value);
this.tabFrameSelectedTab.set(page.getName());
// todo: calculate tab frame scroll bar offset
this.tabFrameScrollBarOffset.set(0);
this.optionPageScrollBarOffset.set(offset);
this.setFocused(false);
this.sodiumVideoOptionsScreen.rebuildGUI();
return true;
}
count++;
}
}
}
}
}
return true;
case Keyboard.KEY_BACK: // GLFW.GLFW_KEY_BACKSPACE
if (this.editable) {
this.selecting = false;
this.erase(-1);
this.selecting = GuiScreen.isShiftKeyDown();
}
return true;
case Keyboard.KEY_DELETE: // GLFW.GLFW_KEY_DELETE
if (this.editable) {
this.selecting = false;
this.erase(1);
this.selecting = GuiScreen.isShiftKeyDown();
}
return true;
case Keyboard.KEY_RIGHT: // GLFW.GLFW_KEY_RIGHT
if (GuiScreen.isCtrlKeyDown()) {
this.setCursor(this.getWordSkipPosition(1));
} else {
this.moveCursor(1);
}
final boolean state = this.getCursor() != this.lastCursorPosition && this.getCursor() != this.text.length() + 1;
this.lastCursorPosition = this.getCursor();
return state;
case Keyboard.KEY_LEFT: // GLFW.GLFW_KEY_LEFT
if (GuiScreen.isCtrlKeyDown()) {
this.setCursor(this.getWordSkipPosition(-1));
} else {
this.moveCursor(-1);
}
final boolean state2 = this.getCursor() != this.lastCursorPosition && this.getCursor() != 0;
this.lastCursorPosition = this.getCursor();
return state2;
case Keyboard.KEY_HOME: // GLFW.GLFW_KEY_HOME
this.setCursorToStart();
return true;
case Keyboard.KEY_END: // GLFW.GLFW_KEY_END
this.setCursorToEnd();
return true;
default:
if (ChatAllowedCharacters.isAllowedCharacter(typedChar)) {
if (this.editable) {
this.lastSearch.set(this.text.trim());
this.write(Character.toString(typedChar));
this.lastSearchIndex.set(0);
}
return true;
}
return false;
}
}
}
}
public int getInnerWidth() {
return this.dim.getWidth() - 12;
}
}
@@ -0,0 +1,64 @@
package me.flashyreese.mods.reeses_sodium_options.client.gui.frame.tab;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.AbstractFrame;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.OptionPageFrame;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.ScrollableFrame;
import me.jellysquid.mods.sodium.client.gui.options.OptionPage;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
public class Tab<T extends AbstractFrame> {
private final String title;
private final Function<Dim2i, T> frameFunction;
public Tab(String title, Function<Dim2i, T> frameFunction) {
this.title = title;
this.frameFunction = frameFunction;
}
public static Builder<?> createBuilder() {
return new Builder<>();
}
public String getTitle() {
return title;
}
public Function<Dim2i, T> getFrameFunction() {
return this.frameFunction;
}
public static class Builder<T extends AbstractFrame> {
private String title;
private Function<Dim2i, T> frameFunction;
public Builder<T> setTitle(String title) {
this.title = title;
return this;
}
public Builder<T> setFrameFunction(Function<Dim2i, T> frameFunction) {
this.frameFunction = frameFunction;
return this;
}
public Tab<T> build() {
return new Tab<>(this.title, this.frameFunction);
}
public Tab<ScrollableFrame> from(OptionPage page, AtomicReference<Integer> verticalScrollBarOffset) {
return new Tab<>(page.getName(), dim2i -> ScrollableFrame
.createBuilder()
.setDimension(dim2i)
.setFrame(OptionPageFrame
.createBuilder()
.setDimension(new Dim2i(dim2i.getOriginX(), dim2i.getOriginY(), dim2i.getWidth(), dim2i.getHeight()))
.setOptionPage(page)
.build())
.setVerticalScrollBarOffset(verticalScrollBarOffset)
.build());
}
}
}
@@ -0,0 +1,202 @@
package me.flashyreese.mods.reeses_sodium_options.client.gui.frame.tab;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.AbstractFrame;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.components.ScrollBarComponent;
import me.jellysquid.mods.sodium.client.gui.widgets.AbstractWidget;
import me.jellysquid.mods.sodium.client.gui.widgets.FlatButtonWidget;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import org.apache.commons.lang3.Validate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
public class TabFrame extends AbstractFrame {
private final boolean tabSectionCanScroll;
private final Dim2i tabSection;
private final Dim2i frameSection;
private final List<Tab<?>> tabs = new ArrayList<>();
private final Runnable onSetTab;
private final AtomicReference<String> tabSectionSelectedTab;
private ScrollBarComponent tabSectionScrollBar = null;
private Tab<?> selectedTab;
private AbstractFrame selectedFrame;
public TabFrame(Dim2i dim, boolean renderOutline, List<Tab<?>> tabs, Runnable onSetTab, AtomicReference<String> tabSectionSelectedTab, AtomicReference<Integer> tabSectionScrollBarOffset) {
super(dim, renderOutline);
this.tabs.addAll(tabs);
final int tabSectionY = this.tabs.size() * 18;
this.tabSectionCanScroll = tabSectionY > this.dim.getHeight();
final Optional<Integer> result = tabs.stream().map(tab -> this.getTextWidth(tab.getTitle())).max(Integer::compareTo);
this.tabSection = new Dim2i(this.dim.getOriginX(), this.dim.getOriginY(), result.map(integer -> integer + (this.tabSectionCanScroll ? 32 : 24)).orElseGet(() -> (int) (this.dim.getWidth() * 0.35D)), this.dim.getHeight());
this.frameSection = new Dim2i(this.tabSection.getLimitX(), this.dim.getOriginY(), this.dim.getWidth() - this.tabSection.getWidth(), this.dim.getHeight());
this.onSetTab = onSetTab;
if (this.tabSectionCanScroll) {
this.tabSectionScrollBar = new ScrollBarComponent(new Dim2i(this.tabSection.getLimitX() - 11, this.tabSection.getOriginY(), 10, this.tabSection.getHeight()), ScrollBarComponent.Mode.VERTICAL, tabSectionY, this.dim.getHeight(), offset -> {
this.buildFrame();
tabSectionScrollBarOffset.set(offset);
}, this.dim);
this.tabSectionScrollBar.setOffset(tabSectionScrollBarOffset.get());
}
this.tabSectionSelectedTab = tabSectionSelectedTab;
if (this.tabSectionSelectedTab.get() != null) {
this.selectedTab = this.tabs.stream().filter(tab -> tab.getTitle().equals(this.tabSectionSelectedTab.get())).findAny().get();
}
this.buildFrame();
// Let's build each frame, future note for anyone: do not move this line.
this.tabs.stream().filter(tab -> this.selectedTab != tab).forEach(tab -> tab.getFrameFunction().apply(this.frameSection));
}
public static Builder createBuilder() {
return new Builder();
}
public void setTab(Tab<?> tab) {
this.selectedTab = tab;
this.tabSectionSelectedTab.set(this.selectedTab.getTitle());
if (this.onSetTab != null) {
this.onSetTab.run();
}
this.buildFrame();
}
@Override
public void buildFrame() {
this.children.clear();
this.drawable.clear();
this.controlElements.clear();
if (this.selectedTab == null) {
if (!this.tabs.isEmpty()) {
// Just use the first tab for now
this.selectedTab = this.tabs.get(0);
}
}
this.rebuildTabs();
this.rebuildTabFrame();
if (this.tabSectionCanScroll) {
this.tabSectionScrollBar.updateThumbPosition();
}
super.buildFrame();
}
@Override
public void render(int mouseX, int mouseY, float delta) {
this.applyScissor(this.dim.getOriginX(), this.dim.getOriginY(), this.dim.getWidth(), this.dim.getHeight(), () -> {
for (AbstractWidget widget: this.children) {
if (widget != this.selectedFrame){
widget.render(mouseX, mouseY, delta);
}
}
});
this.selectedFrame.render(mouseX, mouseY, delta);
if (this.tabSectionCanScroll) {
this.tabSectionScrollBar.render(mouseX, mouseY, delta);
}
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
return (this.dim.containsCursor(mouseX, mouseY) && super.mouseClicked(mouseX, mouseY, button)) || (this.tabSectionCanScroll && this.tabSectionScrollBar.mouseClicked(mouseX, mouseY, button));
}
@Override
public boolean mouseDragged(double mouseX, double mouseY, int button) {
return super.mouseDragged(mouseX, mouseY, button) || (this.tabSectionCanScroll && this.tabSectionScrollBar.mouseDragged(mouseX, mouseY, button));
}
@Override
public boolean mouseReleased(double mouseX, double mouseY, int button) {
return super.mouseReleased(mouseX, mouseY, button) || (this.tabSectionCanScroll && this.tabSectionScrollBar.mouseReleased(mouseX, mouseY, button));
}
@Override
public boolean mouseScrolled(double mouseX, double mouseY, double amount) {
return super.mouseScrolled(mouseX, mouseY, amount) || (this.tabSectionCanScroll && this.tabSectionScrollBar.mouseScrolled(mouseX, mouseY, amount));
}
private void rebuildTabs() {
int offsetY = 0;
for (Tab<?> tab : this.tabs) {
final int x = this.tabSection.getOriginX();
final int y = this.tabSection.getOriginY() + offsetY - (this.tabSectionCanScroll ? this.tabSectionScrollBar.getOffset() : 0);
final int width = this.tabSection.getWidth() - (this.tabSectionCanScroll ? 12 : 4);
final int height = 18;
final Dim2i tabDim = new Dim2i(x, y, width, height);
FlatButtonWidget button = new FlatButtonWidget(tabDim, tab.getTitle(), () -> this.setTab(tab));
button.setSelected(this.selectedTab == tab);
button.setLeftAligned(true);
this.children.add(button);
offsetY += 18;
}
}
private void rebuildTabFrame() {
if (this.selectedTab == null) return;
AbstractFrame frame = this.selectedTab.getFrameFunction().apply(this.frameSection);
if (frame != null) {
this.selectedFrame = frame;
frame.buildFrame();
this.children.add(frame);
}
}
public static class Builder {
private final List<Tab<?>> functions = new ArrayList<>();
private Dim2i dim;
private boolean renderOutline;
private Runnable onSetTab;
private AtomicReference<String> tabSectionSelectedTab = new AtomicReference<>(null);
private AtomicReference<Integer> tabSectionScrollBarOffset = new AtomicReference<>(0);
public Builder setDimension(Dim2i dim) {
this.dim = dim;
return this;
}
public Builder shouldRenderOutline(boolean renderOutline) {
this.renderOutline = renderOutline;
return this;
}
public Builder addTabs(Consumer<List<Tab<?>>> tabs) {
tabs.accept(this.functions);
return this;
}
public Builder onSetTab(Runnable onSetTab) {
this.onSetTab = onSetTab;
return this;
}
public Builder setTabSectionSelectedTab(AtomicReference<String> tabSectionSelectedTab) {
this.tabSectionSelectedTab = tabSectionSelectedTab;
return this;
}
public Builder setTabSectionScrollBarOffset(AtomicReference<Integer> tabSectionScrollBarOffset) {
this.tabSectionScrollBarOffset = tabSectionScrollBarOffset;
return this;
}
public TabFrame build() {
Validate.notNull(this.dim, "Dimension must be specified");
return new TabFrame(this.dim, this.renderOutline, this.functions, this.onSetTab, this.tabSectionSelectedTab, this.tabSectionScrollBarOffset);
}
}
}
@@ -0,0 +1,75 @@
package me.flashyreese.mods.reeses_sodium_options.util;
import me.jellysquid.mods.sodium.client.gui.options.Option;
import me.jellysquid.mods.sodium.client.gui.options.OptionPage;
import java.util.ArrayList;
import java.util.List;
public class StringUtils {
// Levenshtein distance: Calculates the number of edits (insertion, deletion, substitution) needed to transform one string into another.
public static int levenshteinDistance(String s1, String s2) {
int m = s1.length();
int n = s2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
dp[i][0] = i;
}
for (int j = 0; j <= n; j++) {
dp[0][j] = j;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
int cost = s1.charAt(i - 1) == s2.charAt(j - 1) ? 0 : 1;
dp[i][j] = Math.min(dp[i - 1][j] + 1, Math.min(dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost));
}
}
return dp[m][n];
}
public static List<Option<?>> fuzzySearch(List<OptionPage> pages, String userInput, int maxDistance) {
List<Option<?>> result = new ArrayList<>();
String[] targetWords = userInput.toLowerCase().split("\\s+");
for (OptionPage page : pages) {
for (Option<?> option : page.getOptions()) {
String sentence = (option.getName()/* +
" " +
option.getTooltip().getString()+
" " +
option.getImpact().toString()*/).toLowerCase();
boolean containsAllWords = true;
for (String word : targetWords) {
boolean containsWord = false;
for (String sentenceWord : sentence.toLowerCase().split("\\s+")) {
int distance = levenshteinDistance(word, sentenceWord);
if (distance <= maxDistance) {
containsWord = true;
break;
}
// Starts with match
if (sentenceWord.startsWith(word)) {
containsWord = true;
break;
}
}
if (!containsWord) {
containsAllWords = false;
break;
}
}
if (containsAllWords) {
result.add(option);
}
}
}
return result;
}
}
@@ -1,6 +1,7 @@
package me.jellysquid.mods.sodium.client;
import com.gtnewhorizons.angelica.Tags;
import com.gtnewhorizons.angelica.config.ConfigMigrator;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
@@ -56,7 +57,7 @@ public class SodiumClientMod {
}
private static SodiumGameOptions loadConfig() {
return SodiumGameOptions.load(Minecraft.getMinecraft().mcDataDir.toPath().resolve("config").resolve("rubidium-options.json"));
return SodiumGameOptions.load(ConfigMigrator.handleConfigMigration("angelica-options.json"));
}
public static String getVersion() {
@@ -3,6 +3,7 @@ package me.jellysquid.mods.sodium.client.gui;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import jss.notfine.core.Settings;
import me.flashyreese.mods.reeses_sodium_options.client.gui.ReeseSodiumVideoOptionsScreen;
import me.jellysquid.mods.sodium.client.gui.options.OptionFlag;
import me.jellysquid.mods.sodium.client.gui.options.OptionGroup;
import me.jellysquid.mods.sodium.client.gui.options.OptionImpact;
@@ -76,6 +77,8 @@ public class SodiumGameOptionPages {
.setBinding((opts, value) -> opts.gammaSetting = value * 0.01F, (opts) -> (int) (opts.gammaSetting / 0.01F))
.build());
firstGroupBuilder.add(Settings.MODE_SKY.option);
firstGroupBuilder.add(Settings.MODE_SUN_MOON.option);
firstGroupBuilder.add(Settings.MODE_STARS.option);
firstGroupBuilder.add(OptionImpl.createBuilder(boolean.class, vanillaOpts)
.setName(I18n.format("sodium.options.clouds.name"))
.setTooltip(I18n.format("sodium.options.clouds.tooltip"))
@@ -94,7 +97,10 @@ public class SodiumGameOptionPages {
.setBinding((opts, value) -> {
opts.guiScale = value;
// Resizing our window
if(Minecraft.getMinecraft().currentScreen instanceof SodiumOptionsGUI oldGui) {
if(Minecraft.getMinecraft().currentScreen instanceof ReeseSodiumVideoOptionsScreen oldGui) {
Minecraft.getMinecraft().displayGuiScreen(new ReeseSodiumVideoOptionsScreen(oldGui.prevScreen));
}
else if(Minecraft.getMinecraft().currentScreen instanceof SodiumOptionsGUI oldGui) {
Minecraft.getMinecraft().displayGuiScreen(new SodiumOptionsGUI(oldGui.prevScreen));
}
}, opts -> opts.guiScale)
@@ -177,7 +183,8 @@ public class SodiumGameOptionPages {
.setBinding((opts, value) -> opts.quality.weatherQuality = value, opts -> opts.quality.weatherQuality)
.setImpact(OptionImpact.MEDIUM)
.build())
.add(OptionImpl.createBuilder(GraphicsQuality.class, sodiumOpts)
.add(AngelicaConfig.enableNotFineFeatures ? Settings.MODE_LEAVES.option :
OptionImpl.createBuilder(GraphicsQuality.class, sodiumOpts)
.setName(I18n.format("sodium.options.leaves_quality.name"))
.setTooltip(I18n.format("sodium.options.leaves_quality.tooltip"))
.setControl(option -> new CyclingControl<>(option, GraphicsQuality.class))
@@ -1,6 +1,9 @@
package me.jellysquid.mods.sodium.client.gui;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.client.gui.ScrollableGuiScreen;
import com.gtnewhorizons.angelica.compat.mojang.Drawable;
import com.gtnewhorizons.angelica.compat.mojang.Element;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import jss.notfine.gui.GuiCustomMenu;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
@@ -13,8 +16,6 @@ import me.jellysquid.mods.sodium.client.gui.options.control.Control;
import me.jellysquid.mods.sodium.client.gui.options.control.ControlElement;
import me.jellysquid.mods.sodium.client.gui.options.control.element.SodiumControlElementFactory;
import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage;
import me.jellysquid.mods.sodium.client.gui.utils.Drawable;
import me.jellysquid.mods.sodium.client.gui.utils.Element;
import me.jellysquid.mods.sodium.client.gui.utils.URLUtils;
import me.jellysquid.mods.sodium.client.gui.widgets.FlatButtonWidget;
import me.jellysquid.mods.sodium.client.util.Dim2i;
@@ -32,28 +33,29 @@ import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Stream;
public class SodiumOptionsGUI extends GuiScreen {
public class SodiumOptionsGUI extends ScrollableGuiScreen {
private static final SodiumControlElementFactory elementFactory = new SodiumControlElementFactory();
protected static final SodiumControlElementFactory elementFactory = new SodiumControlElementFactory();
private final List<Element> children = new CopyOnWriteArrayList<>();
protected final List<Element> children = new CopyOnWriteArrayList<>();
private final List<OptionPage> pages = new ArrayList<>();
protected final List<OptionPage> pages = new ArrayList<>();
private final List<ControlElement<?>> controls = new ArrayList<>();
private final List<Drawable> drawable = new ArrayList<>();
protected final List<ControlElement<?>> controls = new ArrayList<>();
protected final List<Drawable> drawable = new ArrayList<>();
public final GuiScreen prevScreen;
private OptionPage currentPage;
protected OptionPage currentPage;
private FlatButtonWidget applyButton, closeButton, undoButton;
private FlatButtonWidget donateButton, hideDonateButton;
protected FlatButtonWidget applyButton, closeButton, undoButton;
protected FlatButtonWidget donateButton, hideDonateButton;
private boolean hasPendingChanges;
private ControlElement<?> hoveredElement;
protected boolean hasPendingChanges;
protected ControlElement<?> hoveredElement;
protected OptionPage shaderPacks;
private OptionPage shaderPacks;
public SodiumOptionsGUI(GuiScreen prevScreen) {
this.prevScreen = prevScreen;
@@ -63,7 +65,7 @@ public class SodiumOptionsGUI extends GuiScreen {
this.pages.add(SodiumGameOptionPages.advanced());
this.pages.add(SodiumGameOptionPages.performance());
if(AngelicaConfig.enableIris) {
if (AngelicaConfig.enableIris) {
shaderPacks = new OptionPage(I18n.format("options.iris.shaderPackSelection"), ImmutableList.of());
this.pages.add(shaderPacks);
}
@@ -85,7 +87,7 @@ public class SodiumOptionsGUI extends GuiScreen {
this.rebuildGUI();
}
private void rebuildGUI() {
protected void rebuildGUI() {
this.controls.clear();
this.children.clear();
this.drawable.clear();
@@ -105,8 +107,8 @@ public class SodiumOptionsGUI extends GuiScreen {
this.undoButton = new FlatButtonWidget(new Dim2i(this.width - 211, this.height - 26, 65, 20), I18n.format("sodium.options.buttons.undo"), this::undoChanges);
this.applyButton = new FlatButtonWidget(new Dim2i(this.width - 142, this.height - 26, 65, 20), I18n.format("sodium.options.buttons.apply"), this::applyChanges);
this.closeButton = new FlatButtonWidget(new Dim2i(this.width - 73, this.height - 26, 65, 20), I18n.format("gui.done"), this::onClose);
String donateToJelly = I18n.format("sodium.options.buttons.donate");
int width = 12 + this.fontRendererObj.getStringWidth(donateToJelly);
final String donateToJelly = I18n.format("sodium.options.buttons.donate");
final int width = 12 + this.fontRendererObj.getStringWidth(donateToJelly);
this.donateButton = new FlatButtonWidget(new Dim2i(this.width - width - 32, 6, width, 20), donateToJelly, () -> openDonationPage("https://caffeinemc.net/donate"));
this.hideDonateButton = new FlatButtonWidget(new Dim2i(this.width - 26, 6, 20, 20), "x", this::hideDonationButton);
@@ -133,7 +135,7 @@ public class SodiumOptionsGUI extends GuiScreen {
}
private void hideDonationButton() {
SodiumGameOptions options = SodiumClientMod.options();
final SodiumGameOptions options = SodiumClientMod.options();
options.notifications.hideDonationButton = true;
try {
@@ -147,12 +149,12 @@ public class SodiumOptionsGUI extends GuiScreen {
private void rebuildGUIPages() {
int x = 6;
int y = 6;
final int y = 6;
for (OptionPage page : this.pages) {
int width = 12 + this.fontRendererObj.getStringWidth(page.getName());
final int width = 12 + this.fontRendererObj.getStringWidth(page.getName());
FlatButtonWidget button = new FlatButtonWidget(new Dim2i(x, y, width, 18), page.getName(), () -> this.setPage(page));
final FlatButtonWidget button = new FlatButtonWidget(new Dim2i(x, y, width, 18), page.getName(), () -> this.setPage(page));
button.setSelected(this.currentPage == page);
x += width + 6;
@@ -162,14 +164,14 @@ public class SodiumOptionsGUI extends GuiScreen {
}
private void rebuildGUIOptions() {
int x = 6;
final int x = 6;
int y = 28;
for (OptionGroup group : this.currentPage.getGroups()) {
// Add each option's control element
for (Option<?> option : group.getOptions()) {
Control<?> control = option.getControl();
ControlElement<?> element = control.createElement(new Dim2i(x, y, 200, 18), elementFactory);
final Control<?> control = option.getControl();
final ControlElement<?> element = control.createElement(new Dim2i(x, y, 200, 18), elementFactory);
this.controls.add(element);
//Safe if SodiumControlElementFactory or a compatible ControlElementFactory is used to create element.
@@ -186,6 +188,7 @@ public class SodiumOptionsGUI extends GuiScreen {
@Override
public void drawScreen(int mouseX, int mouseY, float delta) {
super.drawScreen(mouseX, mouseY, delta);
super.drawDefaultBackground();
this.updateControls();
@@ -199,14 +202,18 @@ public class SodiumOptionsGUI extends GuiScreen {
}
}
@Override
public List<? extends Element> children() {
return children;
}
private void updateControls() {
ControlElement<?> hovered = this.getActiveControls()
.filter(ControlElement::isHovered)
.findFirst()
.orElse(null);
boolean hasChanges = this.getAllOptions()
.anyMatch(Option::hasChanged);
boolean hasChanges = this.getAllOptions().anyMatch(Option::hasChanged);
for (OptionPage page : this.pages) {
for (Option<?> option : page.getOptions()) {
@@ -234,28 +241,28 @@ public class SodiumOptionsGUI extends GuiScreen {
}
private void renderOptionTooltip(ControlElement<?> element) {
Dim2i dim = element.getDimensions();
final Dim2i dim = element.getDimensions();
int textPadding = 3;
int boxPadding = 3;
final int textPadding = 3;
final int boxPadding = 3;
int boxWidth = 200;
final int boxWidth = 200;
int boxY = dim.getOriginY();
int boxX = dim.getLimitX() + boxPadding;
final int boxX = dim.getLimitX() + boxPadding;
Option<?> option = element.getOption();
List<String> tooltip = new ArrayList<>(this.fontRendererObj.listFormattedStringToWidth(option.getTooltip(), boxWidth - (textPadding * 2)));
final Option<?> option = element.getOption();
final List<String> tooltip = new ArrayList<>(this.fontRendererObj.listFormattedStringToWidth(option.getTooltip(), boxWidth - (textPadding * 2)));
OptionImpact impact = option.getImpact();
final OptionImpact impact = option.getImpact();
if (impact != null) {
tooltip.add(EnumChatFormatting.GRAY + I18n.format("sodium.options.performance_impact_string", impact.toDisplayString()));
}
int boxHeight = (tooltip.size() * 12) + boxPadding;
int boxYLimit = boxY + boxHeight;
int boxYCutoff = this.height - 40;
final int boxHeight = (tooltip.size() * 12) + boxPadding;
final int boxYLimit = boxY + boxHeight;
final int boxYCutoff = this.height - 40;
// If the box is going to be cutoff on the Y-axis, move it back up the difference
if (boxYLimit > boxYCutoff) {
@@ -299,8 +306,7 @@ public class SodiumOptionsGUI extends GuiScreen {
}
private void undoChanges() {
this.getAllOptions()
.forEach(Option::reset);
this.getAllOptions().forEach(Option::reset);
}
private void openDonationPage(String url) {
@@ -340,9 +346,10 @@ public class SodiumOptionsGUI extends GuiScreen {
}
@Override
protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) {
super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick);
protected void mouseClickMove(int mouseX, int mouseY, int mouseButton, long timeSinceLastClick) {
super.mouseClickMove(mouseX, mouseY, mouseButton, timeSinceLastClick);
this.children.forEach(element -> element.mouseDragged(mouseX, mouseY));
this.children.forEach(element -> element.mouseDragged(mouseX, mouseY, mouseButton));
}
}
@@ -29,4 +29,5 @@ public interface Option<T> {
void applyChanges();
Collection<OptionFlag> getFlags();
}
@@ -1,9 +1,13 @@
package me.jellysquid.mods.sodium.client.gui.options;
import lombok.Getter;
import lombok.Setter;
import me.flashyreese.mods.reeses_sodium_options.client.gui.OptionExtended;
import me.jellysquid.mods.sodium.client.gui.options.binding.GenericBinding;
import me.jellysquid.mods.sodium.client.gui.options.binding.OptionBinding;
import me.jellysquid.mods.sodium.client.gui.options.control.Control;
import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import org.apache.commons.lang3.Validate;
import java.util.Collection;
@@ -13,7 +17,7 @@ import java.util.function.BiConsumer;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
public class OptionImpl<S, T> implements Option<T> {
public class OptionImpl<S, T> implements OptionExtended<T> {
private final OptionStorage<S> storage;
private final OptionBinding<S, T> binding;
@@ -207,4 +211,11 @@ public class OptionImpl<S, T> implements Option<T> {
return new OptionImpl<>(this.storage, this.name, this.tooltip, this.binding, this.control, this.flags, this.impact, this.enabled);
}
}
@Setter @Getter private Dim2i parentDimension;
@Setter @Getter private Dim2i dim2i;
@Setter @Getter private boolean highlight;
@Setter @Getter private boolean selected;
}
@@ -4,8 +4,8 @@ import me.jellysquid.mods.sodium.client.gui.options.Option;
import me.jellysquid.mods.sodium.client.util.Dim2i;
public interface ControlElement<T> {
public boolean isHovered();
public Option<T> getOption();
public Dim2i getDimensions();
boolean isHovered();
Option<T> getOption();
Dim2i getDimensions();
}
@@ -17,7 +17,7 @@ public class CyclingControl<T extends Enum<T>> implements Control<T> {
}
public CyclingControl(Option<T> option, Class<T> enumType, String[] names) {
T[] universe = enumType.getEnumConstants();
final T[] universe = enumType.getEnumConstants();
Validate.isTrue(universe.length == names.length, "Mismatch between universe length and names array length");
Validate.notEmpty(universe, "The enum universe must contain at least one item");
@@ -28,15 +28,15 @@ public class CyclingControl<T extends Enum<T>> implements Control<T> {
}
public CyclingControl(Option<T> option, Class<T> enumType, T[] allowedValues) {
T[] universe = enumType.getEnumConstants();
final T[] universe = enumType.getEnumConstants();
this.option = option;
this.allowedValues = allowedValues;
this.names = new String[universe.length];
for (int i = 0; i < this.names.length; i++) {
String name;
T value = universe[i];
final String name;
final T value = universe[i];
name = I18n.format(value instanceof NamedState namedState ? namedState.getKey() : value.name());
@@ -1,5 +1,6 @@
package me.jellysquid.mods.sodium.client.gui.options.control.element;
import me.flashyreese.mods.reeses_sodium_options.client.gui.OptionExtended;
import me.jellysquid.mods.sodium.client.gui.options.Option;
import me.jellysquid.mods.sodium.client.gui.options.control.ControlElement;
import me.jellysquid.mods.sodium.client.gui.widgets.AbstractWidget;
@@ -14,6 +15,9 @@ public class SodiumControlElement<T> extends AbstractWidget implements ControlEl
public SodiumControlElement(Option<T> option, Dim2i dim) {
this.option = option;
this.dim = dim;
if(option instanceof OptionExtended<?> optionExtended) {
optionExtended.setDim2i(dim);
}
}
@Override
@@ -39,6 +43,14 @@ public class SodiumControlElement<T> extends AbstractWidget implements ControlEl
this.drawRect(this.dim.getOriginX(), this.dim.getOriginY(), this.dim.getLimitX(), this.dim.getLimitY(), this.hovered ? 0xE0000000 : 0x90000000);
if(option instanceof OptionExtended<?> optionExtended && (optionExtended.isHighlight())) {
final String replacement = optionExtended.isSelected() ? EnumChatFormatting.DARK_GREEN.toString() : EnumChatFormatting.YELLOW.toString();
label = label.replace(EnumChatFormatting.WHITE.toString(), EnumChatFormatting.WHITE + replacement);
label = label.replace(EnumChatFormatting.STRIKETHROUGH.toString(), EnumChatFormatting.STRIKETHROUGH + replacement);
label = label.replace(EnumChatFormatting.ITALIC.toString(), EnumChatFormatting.ITALIC + replacement);
}
this.drawString(label, this.dim.getOriginX() + 6, this.dim.getCenterY() - 4, 0xFFFFFFFF);
}
@@ -1,5 +1,6 @@
package me.jellysquid.mods.sodium.client.gui.options.control.element;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import me.jellysquid.mods.sodium.client.gui.options.Option;
import me.jellysquid.mods.sodium.client.gui.options.control.ControlElement;
import me.jellysquid.mods.sodium.client.gui.options.control.ControlValueFormatter;
@@ -56,12 +57,22 @@ public class SodiumControlElementFactory implements ControlElementFactory {
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (this.option.isAvailable() && button == 0 && this.dim.containsCursor(mouseX, mouseY)) {
this.currentIndex = (this.option.getValue().ordinal() + 1) % this.allowedValues.length;
this.option.setValue(this.allowedValues[this.currentIndex]);
this.playClickSound();
if(AngelicaConfig.enableReesesSodiumOptions) {
if (this.option.isAvailable() && this.dim.containsCursor(mouseX, mouseY) && (button == 0 || button == 1)) {
this.currentIndex = Math.floorMod(this.option.getValue().ordinal() + (button == 0 ? 1 : -1), this.allowedValues.length);
this.option.setValue(this.allowedValues[this.currentIndex]);
this.playClickSound();
return true;
return true;
}
} else {
if (this.option.isAvailable() && button == 0 && this.dim.containsCursor(mouseX, mouseY)) {
this.currentIndex = (this.option.getValue().ordinal() + 1) % this.allowedValues.length;
this.option.setValue(this.allowedValues[this.currentIndex]);
this.playClickSound();
return true;
}
}
return false;
@@ -176,7 +187,7 @@ public class SodiumControlElementFactory implements ControlElementFactory {
}
@Override
public boolean mouseDragged(double mouseX, double mouseY) {
public boolean mouseDragged(double mouseX, double mouseY, int button) {
if (this.option.isAvailable() && this.sliderBounds.contains((int) mouseX, (int) mouseY)) {
this.setValueFromMouse(mouseX);
@@ -1,5 +0,0 @@
package me.jellysquid.mods.sodium.client.gui.utils;
public interface Drawable {
void render(int mouseX, int mouseY, float delta);
}
@@ -1,11 +0,0 @@
package me.jellysquid.mods.sodium.client.gui.utils;
public interface Element {
default boolean mouseClicked(double mouseX, double mouseY, int button) {
return false;
}
default boolean mouseDragged(double mouseX, double mouseY) {
return false;
}
}
@@ -1,8 +1,8 @@
package me.jellysquid.mods.sodium.client.gui.widgets;
import com.gtnewhorizons.angelica.compat.mojang.Drawable;
import com.gtnewhorizons.angelica.compat.mojang.Element;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import me.jellysquid.mods.sodium.client.gui.utils.Drawable;
import me.jellysquid.mods.sodium.client.gui.utils.Element;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.client.gui.FontRenderer;
@@ -24,10 +24,10 @@ public abstract class AbstractWidget implements Drawable, Element {
}
protected void drawRect(double x1, double y1, double x2, double y2, int color) {
float a = (float) (color >> 24 & 255) / 255.0F;
float r = (float) (color >> 16 & 255) / 255.0F;
float g = (float) (color >> 8 & 255) / 255.0F;
float b = (float) (color & 255) / 255.0F;
final float a = (float) (color >> 24 & 255) / 255.0F;
final float r = (float) (color >> 16 & 255) / 255.0F;
final float g = (float) (color >> 8 & 255) / 255.0F;
final float b = (float) (color & 255) / 255.0F;
this.drawQuads(vertices -> addQuad(vertices, x1, y1, x2, y2, a, r, g, b));
}
@@ -37,7 +37,7 @@ public abstract class AbstractWidget implements Drawable, Element {
GL11.glDisable(GL11.GL_TEXTURE_2D);
GLStateManager.defaultBlendFunc();
Tessellator tessellator = Tessellator.instance;
final Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
consumer.accept(tessellator);
tessellator.draw();
@@ -1,6 +1,7 @@
package me.jellysquid.mods.sodium.client.gui.widgets;
import me.jellysquid.mods.sodium.client.gui.utils.Drawable;
import com.gtnewhorizons.angelica.compat.mojang.Drawable;
import lombok.Setter;
import me.jellysquid.mods.sodium.client.util.Dim2i;
public class FlatButtonWidget extends AbstractWidget implements Drawable {
@@ -8,9 +9,10 @@ public class FlatButtonWidget extends AbstractWidget implements Drawable {
private final String label;
private final Runnable action;
private boolean selected;
private boolean enabled = true;
private boolean visible = true;
@Setter private boolean selected;
@Setter private boolean enabled = true;
@Setter private boolean visible = true;
@Setter private boolean leftAligned;
public FlatButtonWidget(Dim2i dim, String label, Runnable action) {
this.dim = dim;
@@ -24,25 +26,23 @@ public class FlatButtonWidget extends AbstractWidget implements Drawable {
return;
}
boolean hovered = this.dim.containsCursor(mouseX, mouseY);
final boolean hovered = this.dim.containsCursor(mouseX, mouseY);
int backgroundColor = this.enabled ? (hovered ? 0xE0000000 : 0x90000000) : 0x60000000;
int textColor = this.enabled ? 0xFFFFFFFF : 0x90FFFFFF;
final int backgroundColor = this.enabled ? (hovered ? 0xE0000000 : 0x90000000) : 0x60000000;
final int textColor = this.enabled ? 0xFFFFFFFF : 0x90FFFFFF;
int strWidth = this.font.getStringWidth(this.label);
final int strWidth = this.font.getStringWidth(this.label);
this.drawRect(this.dim.getOriginX(), this.dim.getOriginY(), this.dim.getLimitX(), this.dim.getLimitY(), backgroundColor);
this.drawString(this.label, this.dim.getCenterX() - (strWidth / 2), this.dim.getCenterY() - 4, textColor);
final int x = leftAligned ? this.dim.getOriginX() + 10 : this.dim.getCenterX() - (strWidth / 2);
this.drawString(this.label, x, this.dim.getCenterY() - 4, textColor);
if (this.enabled && this.selected) {
this.drawRect(this.dim.getOriginX(), this.dim.getLimitY() - 1, this.dim.getLimitX(), this.dim.getLimitY(), 0xFF94E4D3);
this.drawRect(this.dim.getOriginX(), leftAligned ? this.dim.getOriginY() : (this.dim.getLimitY() - 1),
this.leftAligned ? (this.dim.getOriginX() + 1) : this.dim.getLimitX(), this.dim.getLimitY(), 0xFF94E4D3);
}
}
public void setSelected(boolean selected) {
this.selected = selected;
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (!this.enabled || !this.visible) {
@@ -59,11 +59,4 @@ public class FlatButtonWidget extends AbstractWidget implements Drawable {
return false;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
}
@@ -1,5 +1,6 @@
package me.jellysquid.mods.sodium.client.model.vertex.buffer;
import com.gtnewhorizons.angelica.compat.lwjgl.CompatMemoryUtil;
import me.jellysquid.mods.sodium.client.gl.attribute.BufferVertexFormat;
import org.lwjgl.BufferUtils;
@@ -24,14 +25,7 @@ public class VertexBufferBuilder implements VertexBufferView {
// The new capacity will at least as large as the write it needs to service
final int cap = Math.max(this.capacity * 2, this.capacity + len);
// Allocate a new buffer and copy the old buffer's contents into it
final ByteBuffer buffer = BufferUtils.createByteBuffer(cap);
this.buffer.rewind();
buffer.put(this.buffer);
buffer.position(0);
// Update the buffer and capacity now
this.buffer = buffer;
this.buffer = CompatMemoryUtil.memReallocDirect(this.buffer, cap);
this.capacity = cap;
}
@@ -6,6 +6,7 @@ import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.mixins.interfaces.ITexturesCache;
import com.gtnewhorizons.angelica.rendering.AngelicaBlockSafetyRegistry;
import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue;
import it.unimi.dsi.fastutil.longs.LongArrayFIFOQueue;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import me.jellysquid.mods.sodium.client.render.chunk.ChunkGraphicsState;
import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderContainer;
@@ -89,20 +90,21 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
private boolean rendersOffThread(Block block) {
final int type = block.getRenderType();
return type < 42 && type != 22 && AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block);
return (type < 42 && type != 22 && AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block, false)) || AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block, true);
}
private void handleRenderBlocksTextures(RenderBlocks rb, ChunkRenderData.Builder builder) {
if(!AngelicaConfig.speedupAnimations || !(rb instanceof ITexturesCache)) return;
for(IIcon texture : ((ITexturesCache)rb).getRenderedTextures()) {
if(texture instanceof TextureAtlasSprite) {
builder.addSprite((TextureAtlasSprite)texture);
if(texture instanceof TextureAtlasSprite textureAtlasSprite) {
builder.addSprite(textureAtlasSprite);
}
}
}
@Override
public ChunkBuildResult<T> performBuild(ChunkRenderCacheLocal cache, ChunkBuildBuffers buffers, CancellationSource cancellationSource) {
// COMPATIBLITY NOTE: Oculus relies on the LVT of this method being unchanged, at least in 16.5
final ChunkRenderData.Builder renderData = new ChunkRenderData.Builder();
final ChunkOcclusionDataBuilder occluder = new ChunkOcclusionDataBuilder();
final ChunkRenderBounds.Builder bounds = new ChunkRenderBounds.Builder();
@@ -118,9 +120,10 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
final int baseY = this.render.getOriginY();
final int baseZ = this.render.getOriginZ();
final BlockPos.Mutable pos = new BlockPos.Mutable();
final BlockPos pos = new BlockPos();
final BlockPos renderOffset = this.offset;
final LongArrayFIFOQueue mainThreadBlocks = new LongArrayFIFOQueue();
boolean hasMainThreadBlocks = false;
for (int relY = 0; relY < 16; relY++) {
@@ -158,6 +161,7 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
}
}
} else {
mainThreadBlocks.enqueue(pos.asLong());
hasMainThreadBlocks = true;
}
@@ -198,7 +202,7 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
if(hasMainThreadBlocks) {
// Render the other blocks on the main thread
try {
CompletableFuture.runAsync(() -> this.performMainBuild(cache, buffers, cancellationSource, bounds, renderData), AngelicaRenderQueue.executor()).get();
CompletableFuture.runAsync(() -> this.performMainBuild(cache, buffers, cancellationSource, bounds, renderData, mainThreadBlocks), AngelicaRenderQueue.executor()).get();
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
return null;
@@ -228,54 +232,51 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
/**
* Render the blocks that should be rendered on the main thread.
*
* TODO: Deduplicate this with the main method above.
*/
private void performMainBuild(ChunkRenderCacheLocal cache, ChunkBuildBuffers buffers, CancellationSource cancellationSource, ChunkRenderBounds.Builder bounds, ChunkRenderData.Builder renderData) {
private void performMainBuild(ChunkRenderCacheLocal cache, ChunkBuildBuffers buffers, CancellationSource cancellationSource, ChunkRenderBounds.Builder bounds, ChunkRenderData.Builder renderData, LongArrayFIFOQueue mainThreadBlocks) {
final WorldSlice slice = cache.getWorldSlice();
final BlockPos.Mutable pos = new BlockPos.Mutable();
final BlockPos pos = new BlockPos();
final int baseX = this.render.getOriginX();
final int baseY = this.render.getOriginY();
final int baseZ = this.render.getOriginZ();
final BlockPos renderOffset = this.offset;
final RenderBlocks rb = new RenderBlocks(slice.getWorld());
for (int relY = 0; relY < 16; relY++) {
while(!mainThreadBlocks.isEmpty()) {
final long longPos = mainThreadBlocks.dequeueLong();
if (cancellationSource.isCancelled()) {
return;
}
for (int relZ = 0; relZ < 16; relZ++) {
for (int relX = 0; relX < 16; relX++) {
final Block block = slice.getBlockRelative(relX + 16, relY + 16, relZ + 16);
pos.set(longPos);
final int relX = pos.getX() - baseX;
final int relY = pos.getY() - baseY;
final int relZ = pos.getZ() - baseZ;
final Block block = slice.getBlockRelative(relX + 16, relY + 16, relZ + 16);
// Only render blocks that need main thread assistance
if (block.getMaterial() == Material.air || rendersOffThread(block)) {
continue;
// Only render blocks that need main thread assistance
if (block.getMaterial() == Material.air || rendersOffThread(block)) {
continue;
}
// TODO: Collect data on which render types are hitting this code path most often so mods can be updated slowly
final int meta = slice.getBlockMetadataRelative(relX + 16, relY + 16, relZ + 16);
buffers.setRenderOffset(pos.x - renderOffset.getX(), pos.y - renderOffset.getY(), pos.z - renderOffset.getZ());
if(AngelicaConfig.enableIris) buffers.iris$setLocalPos(relX, relY, relZ);
// Do regular block rendering
for (BlockRenderPass pass : BlockRenderPass.VALUES) {
if (block.canRenderInPass(pass.ordinal()) && (!AngelicaConfig.enableSodiumFluidRendering || !(block instanceof IFluidBlock))) {
final long seed = MathUtil.hashPos(pos.x, pos.y, pos.z);
if(AngelicaConfig.enableIris) buffers.iris$setMaterialId(block, ExtendedDataHelper.BLOCK_RENDER_TYPE);
if (cache.getBlockRenderer().renderModel(slice.getWorld(), rb, block, meta, pos, buffers.get(pass), true, seed)) {
bounds.addBlock(relX, relY, relZ);
}
// TODO: Collect data on which render types are hitting this code path most often
// so mods can be updated slowly
final int meta = slice.getBlockMetadataRelative(relX + 16, relY + 16, relZ + 16);
pos.set(baseX + relX, baseY + relY, baseZ + relZ);
buffers.setRenderOffset(pos.x - renderOffset.getX(), pos.y - renderOffset.getY(), pos.z - renderOffset.getZ());
if(AngelicaConfig.enableIris) buffers.iris$setLocalPos(relX, relY, relZ);
// Do regular block rendering
for (BlockRenderPass pass : BlockRenderPass.VALUES) {
if (block.canRenderInPass(pass.ordinal()) && (!AngelicaConfig.enableSodiumFluidRendering || !(block instanceof IFluidBlock))) {
final long seed = MathUtil.hashPos(pos.x, pos.y, pos.z);
if(AngelicaConfig.enableIris) buffers.iris$setMaterialId(block, ExtendedDataHelper.BLOCK_RENDER_TYPE);
if (cache.getBlockRenderer().renderModel(slice.getWorld(), rb, block, meta, pos, buffers.get(pass), true, seed)) {
bounds.addBlock(relX, relY, relZ);
}
}
}
if(AngelicaConfig.enableIris) buffers.iris$resetBlockContext();
}
}
if(AngelicaConfig.enableIris) buffers.iris$resetBlockContext();
}
handleRenderBlocksTextures(rb, renderData);
@@ -58,10 +58,11 @@ public class BlockRenderer {
final CapturingTessellator tess = (CapturingTessellator) TessellatorManager.get();
tess.startDrawingQuads();
// RenderBlocks adds the subchunk-relative coordinates as the offset, cancel it out here
tess.setOffset(pos);
tess.setOffset(pos);
renderBlocks.renderBlockByRenderType(block, pos.x, pos.y, pos.z);
final List<Quad> quads = TessellatorManager.stopCapturingToPooledQuads();
tess.resetOffset();
for (ModelQuadFacing facing : ModelQuadFacing.VALUES) {
this.random.setSeed(seed);
@@ -95,6 +95,7 @@ public class FluidRenderer {
int posZ = pos.z;
Fluid fluid = ((IFluidBlock) block).getFluid();
if(fluid == null) return false;
// Check for occluded sides; if everything is occluded, don't render
boolean sfUp = this.isFluidOccluded(world, posX, posY, posZ, ForgeDirection.UP, fluid);
@@ -1,10 +1,10 @@
package me.jellysquid.mods.sodium.client.util;
public class Dim2i {
private final int x;
private final int y;
private final int width;
private final int height;
private int x;
private int y;
private int width;
private int height;
public Dim2i(int x, int y, int width, int height) {
this.x = x;
@@ -48,4 +48,28 @@ public class Dim2i {
public int getCenterY() {
return this.y + (this.height / 2);
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public boolean canFitDimension(Dim2i anotherDim) {
return this.x <= anotherDim.getOriginX() && this.y <= anotherDim.getOriginY() && this.getLimitX() >= anotherDim.getLimitX() && this.getLimitY() >= anotherDim.getLimitY();
}
public boolean overlapWith(Dim2i other) {
return this.x < other.getLimitX() && this.getLimitX() > other.getOriginX() && this.y < other.getLimitY() && this.getLimitY() > other.getOriginY();
}
}
@@ -88,6 +88,8 @@ public class WorldSlice implements IBlockAccess {
@Getter
private ChunkSectionPos origin;
StructureBoundingBox volume;
public static ChunkRenderContext prepare(World world, ChunkSectionPos origin, ClonedChunkSectionCache sectionCache) {
final Chunk chunk = world.getChunkFromChunkCoords(origin.x, origin.z);
final ExtendedBlockStorage section = chunk.getBlockStorageArray()[origin.y];
@@ -156,6 +158,7 @@ public class WorldSlice implements IBlockAccess {
public void copyData(ChunkRenderContext context) {
this.origin = context.getOrigin();
this.sections = context.getSections();
this.volume = context.getVolume();
this.baseX = (this.origin.x - NEIGHBOR_CHUNK_RADIUS) << 4;
this.baseY = (this.origin.y - NEIGHBOR_CHUNK_RADIUS) << 4;
@@ -167,7 +170,7 @@ public class WorldSlice implements IBlockAccess {
for (int z = 0; z < SECTION_LENGTH; z++) {
final int idx = getLocalSectionIndex(x, y, z);
ClonedChunkSection section = this.sections[idx];
final ClonedChunkSection section = this.sections[idx];
this.unpackBlockData(this.blockArrays[idx], this.metadataArrays[idx], section, context.getVolume());
this.biomeData[idx] = section.getBiomeData();
@@ -227,11 +230,15 @@ public class WorldSlice implements IBlockAccess {
@Override
public BiomeGenBase getBiomeGenForCoords(int x, int z) {
if (!blockBoxContains(this.volume, x, volume.minY, z)) {
return BiomeGenBase.plains;
}
final int relX = x - this.baseX;
final int relY = 0;
final int relZ = z - this.baseZ;
BiomeGenBase biome = this.biomeData[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)]
final BiomeGenBase biome = this.biomeData[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)]
[(x & 15) | (z & 15) << 4];
// can be null if biome wasn't generated yet
return biome == null ? BiomeGenBase.plains : biome;
@@ -274,7 +281,7 @@ public class WorldSlice implements IBlockAccess {
}
private void unpackBlockDataR(Block[] blocks, int metas[], ClonedChunkSection section, StructureBoundingBox box) {
ChunkSectionPos pos = section.getPosition();
final ChunkSectionPos pos = section.getPosition();
final int minBlockX = Math.max(box.minX, pos.getMinX());
final int maxBlockX = Math.min(box.maxX, pos.getMaxX());
@@ -306,6 +313,10 @@ public class WorldSlice implements IBlockAccess {
}
public Block getBlock(int x, int y, int z) {
if (!blockBoxContains(this.volume, x, y, z)) {
return Blocks.air;
}
final int relX = x - this.baseX;
final int relY = y - this.baseY;
final int relZ = z - this.baseZ;
@@ -322,6 +333,9 @@ public class WorldSlice implements IBlockAccess {
@Override
public int getBlockMetadata(int x, int y, int z) {
if (!blockBoxContains(this.volume, x, y, z)) {
return 0;
}
final int relX = x - this.baseX;
final int relY = y - this.baseY;
final int relZ = z - this.baseZ;
@@ -331,22 +345,27 @@ public class WorldSlice implements IBlockAccess {
@Override
public TileEntity getTileEntity(int x, int y, int z) {
int relX = x - this.baseX;
int relY = y - this.baseY;
int relZ = z - this.baseZ;
if (!blockBoxContains(this.volume, x, y, z)) {
return null;
}
final int relX = x - this.baseX;
final int relY = y - this.baseY;
final int relZ = z - this.baseZ;
return this.sections[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)].getBlockEntity(relX & 15, relY & 15, relZ & 15);
}
public int getLightLevel(EnumSkyBlock type, int x, int y, int z) {
if (!blockBoxContains(this.volume, x, y, z)) {
return 0;
}
y = MathHelper.clamp_int(y, 0, 255);
int relX = x - this.baseX;
int relY = y - this.baseY;
int relZ = z - this.baseZ;
NibbleArray lightArray = this.lightArrays[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)][type.ordinal()];
final int relX = x - this.baseX;
final int relY = y - this.baseY;
final int relZ = z - this.baseZ;
final NibbleArray lightArray = this.lightArrays[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)][type.ordinal()];
if (lightArray == null) {
// If the array is null, it means the dimension for the current world does not support that light type
return this.defaultLightValues[type.ordinal()];
@@ -385,4 +404,12 @@ public class WorldSlice implements IBlockAccess {
public World getWorld() {
return this.world;
}
private static boolean blockBoxContains(StructureBoundingBox box, int x, int y, int z) {
return x >= box.minX &&
x <= box.maxX &&
y >= box.minY &&
y <= box.maxY &&
z >= box.minZ &&
z <= box.maxZ;
}
}
@@ -1,10 +1,12 @@
package me.jellysquid.mods.sodium.proxy;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import jss.notfine.gui.GuiCustomMenu;
import me.flashyreese.mods.reeses_sodium_options.client.gui.ReeseSodiumVideoOptionsScreen;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptionPages;
import me.jellysquid.mods.sodium.client.gui.SodiumOptionsGUI;
import net.minecraft.client.Minecraft;
@@ -28,8 +30,10 @@ public class ClientProxy extends CommonProxy {
if(GuiScreen.isShiftKeyDown()) {
Minecraft.getMinecraft().displayGuiScreen(new GuiCustomMenu(eventGui.parentGuiScreen, SodiumGameOptionPages.general(),
SodiumGameOptionPages.quality(), SodiumGameOptionPages.advanced(), SodiumGameOptionPages.performance()));
} else {
} else if(!AngelicaConfig.enableReesesSodiumOptions || GuiScreen.isCtrlKeyDown()) {
Minecraft.getMinecraft().displayGuiScreen(new SodiumOptionsGUI(eventGui.parentGuiScreen));
} else {
Minecraft.getMinecraft().displayGuiScreen(new ReeseSodiumVideoOptionsScreen(eventGui.parentGuiScreen));
}
}
}
-42
View File
@@ -3,16 +3,12 @@ package net.coderbot.iris;
import com.google.common.base.Throwables;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.Tags;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.mitchej123.hodgepodge.Common;
import com.mitchej123.hodgepodge.client.HodgepodgeClient;
import com.mojang.realmsclient.gui.ChatFormatting;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent;
import lombok.Getter;
import net.coderbot.iris.config.IrisConfig;
import net.coderbot.iris.gl.GLDebug;
import net.coderbot.iris.gl.shader.StandardMacros;
import net.coderbot.iris.gui.screen.ShaderPackScreen;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
@@ -38,8 +34,6 @@ import net.minecraft.launchwrapper.Launch;
import net.minecraft.util.ChatComponentText;
import org.jetbrains.annotations.NotNull;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.ContextCapabilities;
import org.lwjgl.opengl.GLContext;
import java.io.IOException;
import java.io.InputStream;
@@ -61,7 +55,6 @@ import java.util.zip.ZipException;
public class Iris {
public final boolean isDevelopmentEnvironment;
public static ContextCapabilities capabilities;
/**
* The user-facing name of the mod. Moved into a constant to facilitate easy branding changes (for forks). You'll still need to change this separately in
@@ -179,9 +172,6 @@ public class Iris {
initialized = true;
}
public static void identifyCapabilities() {
capabilities = GLContext.getCapabilities();
}
/**
* Called once RenderSystem#initRenderer has completed. This means that we can safely access OpenGL.
*/
@@ -192,8 +182,6 @@ public class Iris {
return;
}
setDebug(irisConfig.areDebugOptionsEnabled());
PBRTextureManager.INSTANCE.init();
// Only load the shader pack when we can access OpenGL
@@ -387,34 +375,6 @@ public class Iris {
logger.info("Shaders are disabled");
}
// Temp escalation
public static void setDebug(boolean enable) {
GLStateManager.assertMainThread();
final int success;
if (enable) {
success = GLDebug.setupDebugMessageCallback();
} else {
success = GLDebug.disableDebugMessages();
}
logger.info("Debug functionality is " + (enable ? "enabled, logging will be more verbose!" : "disabled."));
if (Minecraft.getMinecraft().thePlayer != null) {
Minecraft.getMinecraft().thePlayer.sendChatMessage(I18n.format(success != 0 ? (enable
? "iris.shaders.debug.enabled"
: "iris.shaders.debug.disabled") : "iris.shaders.debug.failure"));
if (success == 2) {
Minecraft.getMinecraft().thePlayer.sendChatMessage(I18n.format("iris.shaders.debug.restart"));
}
}
if(Iris.isInitialized()) {
try {
irisConfig.setDebugEnabled(enable);
irisConfig.save();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static Optional<Properties> tryReadConfigProperties(Path path) {
final Properties properties = new Properties();
@@ -545,8 +505,6 @@ public class Iris {
if (Minecraft.getMinecraft().theWorld != null) {
Iris.getPipelineManager().preparePipeline(Iris.getCurrentDimension());
}
// Reload Sodium/Invalidate Chunk Cache
Minecraft.getMinecraft().renderGlobal.loadRenderers();
}
/**
@@ -27,11 +27,6 @@ public class IrisConfig {
*/
private boolean enableShaders;
/**
* If debug features should be enabled. Gives much more detailed OpenGL error outputs at the cost of performance.
*/
private boolean enableDebugOptions;
/**
* If the update notification should be disabled or not.
*/
@@ -42,7 +37,6 @@ public class IrisConfig {
public IrisConfig(Path propertiesPath) {
shaderPackName = null;
enableShaders = true;
enableDebugOptions = false;
disableUpdateMessage = false;
this.propertiesPath = propertiesPath;
}
@@ -97,18 +91,10 @@ public class IrisConfig {
return enableShaders;
}
public boolean areDebugOptionsEnabled() {
return enableDebugOptions;
}
public boolean shouldDisableUpdateMessage() {
return disableUpdateMessage;
}
public void setDebugEnabled(boolean enabled) {
enableDebugOptions = enabled;
}
/**
* Sets whether shaders should be used for rendering.
*/
@@ -134,7 +120,6 @@ public class IrisConfig {
}
shaderPackName = properties.getProperty("shaderPack");
enableShaders = !"false".equals(properties.getProperty("enableShaders"));
enableDebugOptions = "true".equals(properties.getProperty("enableDebugOptions"));
disableUpdateMessage = "true".equals(properties.getProperty("disableUpdateMessage"));
// TODO: GUI
// try {
@@ -161,7 +146,6 @@ public class IrisConfig {
final Properties properties = new Properties();
properties.setProperty("shaderPack", getShaderPackName().orElse(""));
properties.setProperty("enableShaders", enableShaders ? "true" : "false");
properties.setProperty("enableDebugOptions", enableDebugOptions ? "true" : "false");
properties.setProperty("disableUpdateMessage", disableUpdateMessage ? "true" : "false");
// properties.setProperty("maxShadowRenderDistance", String.valueOf(IrisVideoSettings.shadowDistance));
properties.setProperty("maxShadowRenderDistance", String.valueOf(32));
@@ -33,15 +33,15 @@ public class IrisRenderSystem {
public static void initRenderer() {
try {
if (Iris.capabilities.OpenGL45) {
if (GLStateManager.capabilities.OpenGL45) {
dsaState = new DSACore();
Iris.logger.info("OpenGL 4.5 detected, enabling DSA.");
}
hasMultibind = Iris.capabilities.OpenGL45;
hasMultibind = GLStateManager.capabilities.OpenGL45;
} catch (NoSuchFieldError ignored) {}
try {
if (dsaState == null && Iris.capabilities.GL_ARB_direct_state_access) {
if (dsaState == null && GLStateManager.capabilities.GL_ARB_direct_state_access) {
dsaState = new DSAARB();
Iris.logger.info("ARB_direct_state_access detected, enabling DSA.");
}
@@ -51,7 +51,7 @@ public class IrisRenderSystem {
}
try {
hasMultibind |= Iris.capabilities.GL_ARB_multi_bind;
hasMultibind |= GLStateManager.capabilities.GL_ARB_multi_bind;
} catch (NoSuchFieldError ignored) {}
supportsCompute = supportsCompute();
@@ -187,7 +187,7 @@ public class IrisRenderSystem {
}
public static void bindImageTexture(int unit, int texture, int level, boolean layered, int layer, int access, int format) {
if (Iris.capabilities.OpenGL42) {
if (GLStateManager.capabilities.OpenGL42) {
GL42.glBindImageTexture(unit, texture, level, layered, layer, access, format);
} else {
EXTShaderImageLoadStore.glBindImageTextureEXT(unit, texture, level, layered, layer, access, format);
@@ -195,9 +195,9 @@ public class IrisRenderSystem {
}
public static int getMaxImageUnits() {
if (Iris.capabilities.OpenGL42) {
if (GLStateManager.capabilities.OpenGL42) {
return GL11.glGetInteger(GL42.GL_MAX_IMAGE_UNITS);
} else if (Iris.capabilities.GL_EXT_shader_image_load_store) {
} else if (GLStateManager.capabilities.GL_EXT_shader_image_load_store) {
return GL11.glGetInteger(EXTShaderImageLoadStore.GL_MAX_IMAGE_UNITS_EXT);
} else {
return 0;
@@ -223,7 +223,7 @@ public class IrisRenderSystem {
}
public static boolean supportsBufferBlending() {
return Iris.capabilities.GL_ARB_draw_buffers_blend || Iris.capabilities.OpenGL40;
return GLStateManager.capabilities.GL_ARB_draw_buffers_blend || GLStateManager.capabilities.OpenGL40;
}
public static void disableBufferBlend(int buffer) {
@@ -353,7 +353,7 @@ public class IrisRenderSystem {
@Override
public int bufferStorage(int target, FloatBuffer data, int usage) {
int buffer = GL45.glCreateBuffers();
final int buffer = GL45.glCreateBuffers();
GL45.glNamedBufferData(buffer, data, usage);
return buffer;
}
@@ -424,7 +424,7 @@ public class IrisRenderSystem {
@Override
public void copyTexSubImage2D(int destTexture, int target, int i, int i1, int i2, int i3, int i4, int width, int height) {
int previous = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final int previous = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, destTexture);
GL11.glCopyTexSubImage2D(target, i, i1, i2, i3, i4, width, height);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, previous);
@@ -438,7 +438,7 @@ public class IrisRenderSystem {
@Override
public int bufferStorage(int target, FloatBuffer data, int usage) {
int buffer = GL15.glGenBuffers();
final int buffer = GL15.glGenBuffers();
GL15.glBindBuffer(target, buffer);
bufferData(target, data, usage);
GL15.glBindBuffer(target, 0);
@@ -461,14 +461,14 @@ public class IrisRenderSystem {
@Override
public int createFramebuffer() {
int framebuffer = OpenGlHelper.func_153165_e/*glGenFramebuffers*/();
final int framebuffer = OpenGlHelper.func_153165_e/*glGenFramebuffers*/();
OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_FRAMEBUFFER, framebuffer);
return framebuffer;
}
@Override
public int createTexture(int target) {
int texture = GL11.glGenTextures();
final int texture = GL11.glGenTextures();
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
return texture;
}
@@ -496,7 +496,7 @@ public class IrisRenderSystem {
// TODO: Proper notification of compute support
public static boolean supportsCompute() {
try {
return Iris.capabilities.GL_ARB_compute_shader;
return GLStateManager.capabilities.GL_ARB_compute_shader;
} catch(Exception ignored) {
return false;
}
@@ -52,7 +52,11 @@ public class ProgramUniforms {
}
private static long getCurrentTick() {
return Objects.requireNonNull(Minecraft.getMinecraft().theWorld).getWorldTime();
if (Minecraft.getMinecraft().theWorld != null) {
return Minecraft.getMinecraft().theWorld.getWorldTime();
} else {
return 0L;
}
}
public void update() {
@@ -2,7 +2,7 @@
package net.coderbot.iris.gl.shader;
import net.coderbot.iris.gl.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import net.coderbot.iris.gl.GlResource;
import net.coderbot.iris.gl.IrisRenderSystem;
import org.apache.logging.log4j.LogManager;
@@ -2,7 +2,7 @@
package net.coderbot.iris.gl.shader;
import net.coderbot.iris.gl.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import net.coderbot.iris.gl.IrisRenderSystem;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -1,6 +1,6 @@
package net.coderbot.iris.gl.texture;
import net.coderbot.iris.Iris;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import net.coderbot.iris.gl.IrisRenderSystem;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import org.lwjgl.opengl.GL11;
@@ -78,7 +78,7 @@ public interface DepthCopyStrategy {
}
static DepthCopyStrategy fastest(boolean combinedStencilRequired) {
if (Iris.capabilities.GL_ARB_copy_image) {
if (GLStateManager.capabilities.GL_ARB_copy_image) {
return new Gl43CopyImage();
}
@@ -10,6 +10,8 @@ import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import org.joml.Matrix4f;
public class HandRenderer {
@@ -58,7 +60,11 @@ public class HandRenderer {
public boolean isHandTranslucent(InteractionHand hand) {
// TODO: Offhand
// Item item = Minecraft.getMinecraft().thePlayer.getItemBySlot(hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFFHAND : EquipmentSlot.MAINHAND).getItem();
Item item = Minecraft.getMinecraft().thePlayer.getHeldItem().getItem();
ItemStack heldItem = Minecraft.getMinecraft().thePlayer.getHeldItem();
if (heldItem == null) {
return false;
}
Item item = heldItem.getItem();
if (item instanceof ItemBlock itemBlock) {
// TODO: RenderType
@@ -157,7 +157,7 @@ public class HorizonRenderer {
vertexBuffer.bind();
GL11.glVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
vertexBuffer.draw(floatBuffer, GL11.GL_QUADS);
vertexBuffer.draw(floatBuffer);
GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
vertexBuffer.unbind();
}
@@ -39,8 +39,7 @@ public class PipelineManager {
if (BlockRenderingSettings.INSTANCE.isReloadRequired()) {
if (Minecraft.getMinecraft().renderGlobal != null) {
// TODO: Iris
// Minecraft.getMinecraft().renderGlobal.allChanged();
Minecraft.getMinecraft().renderGlobal.loadRenderers();
}
BlockRenderingSettings.INSTANCE.clearReloadRequired();
@@ -2,7 +2,6 @@ package net.coderbot.iris.postprocess;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.IrisRenderSystem;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.gl.program.Program;
@@ -40,7 +39,7 @@ public class CenterDepthSampler {
this.framebuffer = new GlFramebuffer();
// Fall back to a less precise format if the system doesn't support OpenGL 3
InternalTextureFormat format = Iris.capabilities.OpenGL32 ? InternalTextureFormat.R32F : InternalTextureFormat.RGB16;
InternalTextureFormat format = GLStateManager.capabilities.OpenGL32 ? InternalTextureFormat.R32F : InternalTextureFormat.RGB16;
setupColorTexture(texture, format);
setupColorTexture(altTexture, format);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0);
@@ -51,7 +50,7 @@ public class CenterDepthSampler {
try {
String fsh = new String(IOUtils.toByteArray(Objects.requireNonNull(getClass().getResourceAsStream("/centerDepth.fsh"))), StandardCharsets.UTF_8);
if (Iris.capabilities.OpenGL32) {
if (GLStateManager.capabilities.OpenGL32) {
fsh = fsh.replace("VERSIONPLACEHOLDER", "150 compatibility");
} else {
fsh = fsh.replace("#define IS_GL3", "");
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more