1.12.2 Options GUI #18

Merged
embeddedt merged 8 commits from karnatour/celeritas:stonecutter into stonecutter 2025-08-04 12:29:10 -04:00
74 changed files with 5086 additions and 19 deletions

No files matched your search

@@ -17,7 +17,7 @@ public class LWJGLHelper {
public static void convertLwjgl2To3(Project project) {
project.getConfigurations().getByName("minecraftLibraries").getDependencies().removeIf(dep -> Objects.equals(dep.getGroup(), "org.lwjgl.lwjgl"));
project.getDependencies().add("minecraftLibraries", "org.taumc:legacy-lwjgl3:1.1-tau");
project.getDependencies().add("minecraftLibraries", "org.taumc:legacy-lwjgl3:1.2-tau");
addLwjgl3(project, "minecraftLibraries");
}
@@ -30,6 +30,7 @@ public class LWJGLHelper {
for (String component : LWJGL3_COMPONENTS) {
deps.add(configurationName, "org.lwjgl:" + component + ":" + LWJGL3_VERSION);
deps.add(configurationName, "org.lwjgl:" + component + ":" + LWJGL3_VERSION + ":natives-" + "linux");
deps.add(configurationName, "org.lwjgl:" + component + ":" + LWJGL3_VERSION + ":natives-" + "windows");
}
}
}
@@ -1,6 +1,10 @@
package org.taumc.celeritas;
import com.mojang.realmsclient.gui.ChatFormatting;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.launchwrapper.Launch;
@@ -9,6 +13,8 @@ import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLConstructionEvent;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
@@ -18,30 +24,29 @@ import org.embeddedt.embeddium.impl.common.util.MathUtil;
import org.embeddedt.embeddium.impl.common.util.NativeBuffer;
import org.embeddedt.embeddium.impl.gl.device.GLRenderDevice;
import org.taumc.celeritas.impl.command.TogglePassCommand;
import org.taumc.celeritas.impl.gui.SodiumGameOptions;
import org.taumc.celeritas.impl.render.terrain.CeleritasWorldRenderer;
import java.lang.management.ManagementFactory;
@Mod(modid = CeleritasVintage.MODID, useMetadata = true)
public class CeleritasVintage {
public static final String MODID = "celeritas";
private static final Logger LOGGER = LogManager.getLogger("Celeritas");
public static String VERSION;
private static final SodiumGameOptions CONFIG = loadConfig();
@Mod.EventHandler
@EventHandler
public void onConstruct(FMLConstructionEvent event) {
GLRenderDevice.VANILLA_STATE_RESETTER = () -> {
OpenGlHelper.glBindBuffer(OpenGlHelper.GL_ARRAY_BUFFER, 0);
};
GLRenderDevice.VANILLA_STATE_RESETTER = () -> OpenGlHelper.glBindBuffer(OpenGlHelper.GL_ARRAY_BUFFER, 0);
VERSION = Loader.instance().getIndexedModList().get(MODID).getVersion();
MinecraftForge.EVENT_BUS.register(this);
}
@Mod.EventHandler
@EventHandler
public void onInit(FMLInitializationEvent event) {
if ((Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment")) {
ClientCommandHandler.instance.registerCommand(new TogglePassCommand());
}
}
@SubscribeEvent
@@ -87,4 +92,24 @@ public class CeleritasVintage {
public static Logger logger() {
return LOGGER;
}
private static SodiumGameOptions loadConfig() {
try {
return SodiumGameOptions.load();
} catch (Exception e) {
LOGGER.error("Failed to load configuration file", e);
LOGGER.error("Using default configuration file in read-only mode");
SodiumGameOptions config = new SodiumGameOptions();
config.setReadOnly();
return config;
}
}
public static SodiumGameOptions options() {
if (CONFIG == null) {
throw new IllegalStateException("Config not yet available");
} else {
return CONFIG;
}
}
}
@@ -0,0 +1,24 @@
package org.taumc.celeritas.api;
import java.util.List;
import org.taumc.celeritas.api.eventbus.CeleritasEvent;
import org.taumc.celeritas.api.eventbus.EventHandlerRegistrar;
import org.taumc.celeritas.api.options.structure.OptionPage;
public class OptionGUIConstructionEvent extends CeleritasEvent {
public static final EventHandlerRegistrar<OptionGUIConstructionEvent> BUS = new EventHandlerRegistrar<>();
private final List<OptionPage> pages;
public OptionGUIConstructionEvent(List<OptionPage> pages) {
this.pages = pages;
}
public List<OptionPage> getPages() {
return this.pages;
}
public void addPage(OptionPage page) {
this.pages.add(page);
}
}
@@ -0,0 +1,27 @@
package org.taumc.celeritas.api;
import java.util.List;
import org.taumc.celeritas.api.eventbus.CeleritasEvent;
import org.taumc.celeritas.api.eventbus.EventHandlerRegistrar;
import org.taumc.celeritas.api.options.OptionIdentifier;
import org.taumc.celeritas.api.options.structure.Option;
public class OptionGroupConstructionEvent extends CeleritasEvent {
public static final EventHandlerRegistrar<OptionGroupConstructionEvent> BUS = new EventHandlerRegistrar<>();
private final OptionIdentifier<Void> id;
private final List<Option<?>> options;
public OptionGroupConstructionEvent(OptionIdentifier<Void> id, List<Option<?>> options) {
this.id = id;
this.options = options;
}
public List<Option<?>> getOptions() {
return this.options;
}
public OptionIdentifier<Void> getId() {
return this.id;
}
}
@@ -0,0 +1,39 @@
package org.taumc.celeritas.api;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.util.text.ITextComponent;
import org.taumc.celeritas.api.eventbus.CeleritasEvent;
import org.taumc.celeritas.api.eventbus.EventHandlerRegistrar;
import org.taumc.celeritas.api.options.OptionIdentifier;
import org.taumc.celeritas.api.options.structure.OptionGroup;
public class OptionPageConstructionEvent extends CeleritasEvent {
public static final EventHandlerRegistrar<OptionPageConstructionEvent> BUS = new EventHandlerRegistrar<>();
private final OptionIdentifier<Void> id;
private final ITextComponent name;
private final List<OptionGroup> additionalGroups = new ArrayList<>();
public OptionPageConstructionEvent(OptionIdentifier<Void> id, ITextComponent name) {
this.id = id;
this.name = name;
}
public OptionIdentifier<Void> getId() {
return this.id;
}
public ITextComponent getName() {
return this.name;
}
public void addGroup(OptionGroup group) {
this.additionalGroups.add(group);
}
public List<OptionGroup> getAdditionalGroups() {
return Collections.unmodifiableList(this.additionalGroups);
}
}
@@ -0,0 +1,16 @@
package org.taumc.celeritas.api.eventbus;
import net.minecraftforge.fml.common.eventhandler.Event;
/**
* The base class which all Celeritas-posted events are derived from.
* <p>
* On Forge (1.12.2), this class extends FML's Event class.
*/
public abstract class CeleritasEvent extends Event {
@Override
public boolean isCancelable() {
return false;
}
}
@@ -0,0 +1,52 @@
package org.taumc.celeritas.api.eventbus;
import net.minecraftforge.common.MinecraftForge;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Holds a list of event handlers and handles event dispatching.
*/
public class EventHandlerRegistrar<T extends CeleritasEvent> {
private final List<Handler<T>> handlerList = new CopyOnWriteArrayList<>();
public EventHandlerRegistrar() {}
public void addListener(Handler<T> listener) {
handlerList.add(listener);
}
/**
* Post the given event to all registered listeners.
* @param event The event to post
* @return true if the event is cancelable and was canceled, false otherwise
*/
public boolean post(T event) {
boolean canceled = false;
// Skip doing work if the handler list is empty
if(!handlerList.isEmpty()) {
boolean isCancelable = event.isCancelable();
for(Handler<T> handler : handlerList) {
handler.acceptEvent(event);
if(isCancelable && event.isCanceled()) {
canceled = true;
}
}
}
// Dispatch to the platform event bus as well (currently only used on Forge)
canceled |= postPlatformSpecificEvent(event);
return canceled;
}
private static <T extends CeleritasEvent> boolean postPlatformSpecificEvent(T event) {
return MinecraftForge.EVENT_BUS.post(event);
}
@FunctionalInterface
public interface Handler<T extends CeleritasEvent> {
void acceptEvent(T event);
}
}
@@ -0,0 +1,90 @@
package org.taumc.celeritas.api.options;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import java.util.Objects;
import net.minecraft.util.ResourceLocation;
import org.jetbrains.annotations.Nullable;
public final class OptionIdentifier<T> {
private final String modId;
private final String path;
private final Class<T> clz;
private static final ObjectOpenHashSet<OptionIdentifier<?>> IDENTIFIERS = new ObjectOpenHashSet<>();
public static final OptionIdentifier<Void> EMPTY = create("", "", Void.class);
private OptionIdentifier(String modId, String path, Class<T> clz) {
this.modId = modId;
this.path = path;
this.clz = clz;
}
public String getModId() {
return this.modId;
}
public String getPath() {
return this.path;
}
public Class<T> getType() {
return this.clz;
}
public static OptionIdentifier<Void> create(ResourceLocation location) {
return create(location, Void.TYPE);
}
public static <T> OptionIdentifier<T> create(ResourceLocation location, Class<T> clz) {
return create(location.getNamespace(), location.getPath(), clz);
}
public static OptionIdentifier<Void> create(String modId, String path) {
return create(modId, path, Void.TYPE);
}
@SuppressWarnings("unchecked")
public static synchronized <T> OptionIdentifier<T> create(String modId, String path, Class<T> clz) {
OptionIdentifier<T> ourIdentifier = new OptionIdentifier<>(modId, path, clz);
OptionIdentifier<T> oldIdentifier = (OptionIdentifier<T>)IDENTIFIERS.addOrGet(ourIdentifier);
if(oldIdentifier != null && oldIdentifier.clz != ourIdentifier.clz) {
throw new IllegalArgumentException(String.format("OptionIdentifier '%s' created with differing class type %s from existing instance %s", ourIdentifier, ourIdentifier.clz, oldIdentifier.clz));
}
return oldIdentifier;
}
public static boolean isPresent(@Nullable OptionIdentifier<?> id) {
return id != null && id != EMPTY;
}
public boolean matches(OptionIdentifier<?> other) {
return this == other;
}
public boolean matches(ResourceLocation other) {
return this.modId.equals(other.getNamespace()) && this.path.equals(other.getPath());
}
@Override
public String toString() {
return this.modId + ":" + this.path;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o != null && this.getClass() == o.getClass()) {
OptionIdentifier<?> that = (OptionIdentifier<?>)o;
return Objects.equals(this.modId, that.modId) && Objects.equals(this.path, that.path);
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(this.modId, this.path);
}
}
@@ -0,0 +1,24 @@
package org.taumc.celeritas.api.options.binding;
import java.util.function.BiConsumer;
import java.util.function.Function;
public class GenericBinding<S, T> implements OptionBinding<S, T> {
private final BiConsumer<S, T> setter;
private final Function<S, T> getter;
public GenericBinding(BiConsumer<S, T> setter, Function<S, T> getter) {
this.setter = setter;
this.getter = getter;
}
@Override
public void setValue(S storage, T value) {
this.setter.accept(storage, value);
}
@Override
public T getValue(S storage) {
return this.getter.apply(storage);
}
}
@@ -0,0 +1,7 @@
package org.taumc.celeritas.api.options.binding;
public interface OptionBinding<S, T> {
void setValue(S var1, T var2);
T getValue(S var1);
}
@@ -0,0 +1,22 @@
package org.taumc.celeritas.api.options.binding.compat;
import net.minecraft.client.settings.GameSettings;
import org.taumc.celeritas.api.options.binding.OptionBinding;
public class VanillaBooleanOptionBinding implements OptionBinding<GameSettings, Boolean> {
private final GameSettings.Options option;
public VanillaBooleanOptionBinding(GameSettings.Options option) {
this.option = option;
}
@Override
public void setValue(GameSettings settings, Boolean value) {
settings.setOptionValue(this.option, value ? 1 : 0);
}
@Override
public Boolean getValue(GameSettings settings) {
return settings.getOptionOrdinalValue(this.option);
}
}
@@ -0,0 +1,12 @@
package org.taumc.celeritas.api.options.control;
import org.taumc.celeritas.api.options.structure.Option;
import org.taumc.celeritas.impl.util.Dim2i;
public interface Control<T> {
Option<T> getOption();
ControlElement<T> createElement(Dim2i var1);
int getMaxWidth();
}
@@ -0,0 +1,65 @@
package org.taumc.celeritas.api.options.control;
import net.minecraft.util.text.TextFormatting;
import org.jetbrains.annotations.NotNull;
import org.taumc.celeritas.api.options.structure.Option;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.gui.widgets.AbstractWidget;
import org.taumc.celeritas.impl.gui.widgets.FlatButtonWidget;
import org.taumc.celeritas.impl.gui.widgets.FlatButtonWidget.Style;
import org.taumc.celeritas.impl.util.Dim2i;
public class ControlElement<T> extends AbstractWidget implements OptionControlElement<T> {
protected final Option<T> option;
protected final Dim2i dim;
private final @NotNull FlatButtonWidget.Style style = FlatButtonWidget.Style.defaults();
public ControlElement(Option<T> option, Dim2i dim) {
this.option = option;
this.dim = dim;
}
@Override
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) {
String name = this.option.getName().getFormattedText();
String label;
if ((this.hovered || this.isFocused()) && this.font.getStringWidth(name) > (this.dim.width() - this.option.getControl().getMaxWidth())) {
name = name.substring(0, Math.min(name.length(), 10)) + "...";
}
if (this.option.isAvailable()) {
if (this.option.hasChanged()) {
label = TextFormatting.ITALIC + name + " *";
} else {
label = TextFormatting.WHITE + name;
}
} else {
label = String.valueOf(TextFormatting.GRAY) + TextFormatting.STRIKETHROUGH + name;
}
this.hovered = this.dim.containsCursor(mouseX, mouseY);
this.drawRect(drawContext, this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), this.hovered ? this.style.bgHovered : this.style.bgDefault);
this.drawString(drawContext, label, this.dim.x() + 6, this.dim.getCenterY() - 4, this.style.textDefault);
if (this.isFocused()) {
this.drawBorder(drawContext, this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), -1);
}
}
public Option<T> getOption() {
return this.option;
}
public Dim2i getDimensions() {
return this.dim;
}
@Override
public boolean isMouseOver(double x, double y) {
return this.dim.containsCursor(x, y);
}
}
@@ -0,0 +1,52 @@
package org.taumc.celeritas.api.options.control;
import net.minecraft.util.text.ITextComponent;
import org.taumc.celeritas.impl.util.ComponentUtil;
public interface ControlValueFormatter {
static ControlValueFormatter guiScale() {
return (v) -> v == 0 ? ComponentUtil.translatable("options.guiScale.auto") : ComponentUtil.literal(v + "x");
}
static ControlValueFormatter fpsLimit() {
return (v) -> v == 260 ? ComponentUtil.translatable("options.framerateLimit.max") : ComponentUtil.translatable("options.framerate", v);
}
static ControlValueFormatter brightness() {
return (v) -> {
if (v == 0) {
return ComponentUtil.translatable("options.gamma.min");
} else if (v == 100) {
return ComponentUtil.translatable("options.gamma.max");
} else {
return ComponentUtil.literal(v + "%");
}
};
}
static ControlValueFormatter biomeBlend() {
return (v) -> v == 0 ? ComponentUtil.translatable("gui.none") : ComponentUtil.translatable("sodium.options.biome_blend.value", v);
}
ITextComponent format(int var1);
static ControlValueFormatter translateVariable(String key) {
return (v) -> ComponentUtil.translatable(key, v);
}
static ControlValueFormatter percentage() {
return (v) -> ComponentUtil.literal(v + "%");
}
static ControlValueFormatter multiplier() {
return (v) -> ComponentUtil.literal(v + "x");
}
static ControlValueFormatter quantityOrDisabled(String name, String disableText) {
return (v) -> ComponentUtil.literal(v == 0 ? disableText : v + " " + name);
}
static ControlValueFormatter number() {
return (v) -> ComponentUtil.literal(String.valueOf(v));
}
}
@@ -0,0 +1,144 @@
package org.taumc.celeritas.api.options.control;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextFormatting;
import org.taumc.celeritas.api.options.structure.Option;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.gui.options.TextProvider;
import org.taumc.celeritas.impl.util.ComponentUtil;
import org.taumc.celeritas.impl.util.Dim2i;
import org.apache.commons.lang3.Validate;
public class CyclingControl<T extends Enum<T>> implements Control<T> {
private final Option<T> option;
private final T[] allowedValues;
private final ITextComponent[] names;
public CyclingControl(Option<T> option, Class<T> enumType) {
this(option, enumType, enumType.getEnumConstants());
}
public CyclingControl(Option<T> option, Class<T> enumType, ITextComponent[] names) {
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");
this.option = option;
this.allowedValues = universe;
this.names = names;
}
public CyclingControl(Option<T> option, Class<T> enumType, T[] allowedValues) {
T[] universe = enumType.getEnumConstants();
this.option = option;
this.allowedValues = allowedValues;
this.names = new ITextComponent[universe.length];
for (int i = 0; i < this.names.length; i++) {
ITextComponent name;
T value = universe[i];
if (value instanceof TextProvider) {
name = ((TextProvider) value).getLocalizedName();
} else {
name = ComponentUtil.literal(value.name());
}
this.names[i] = name;
}
}
public ITextComponent[] getNames() {
return this.names;
}
@Override
public Option<T> getOption() {
return this.option;
}
@Override
public ControlElement<T> createElement(Dim2i dim) {
return new CyclingControlElement<>(this.option, dim, this.allowedValues, this.names);
}
@Override
public int getMaxWidth() {
return 70;
}
private static class CyclingControlElement<T extends Enum<T>> extends ControlElement<T> {
private final T[] allowedValues;
private final ITextComponent[] names;
public CyclingControlElement(Option<T> option, Dim2i dim, T[] allowedValues, ITextComponent[] names) {
super(option, dim);
this.allowedValues = allowedValues;
this.names = names;
}
private int getCurrentIndex() {
for (int i = 0; i < allowedValues.length; i++) {
if (allowedValues[i] == option.getValue()) {
return i;
}
}
return 0;
}
@Override
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) {
super.render(drawContext, mouseX, mouseY, delta);
Enum<T> value = this.option.getValue();
ITextComponent name = this.names[value.ordinal()];
if(!this.option.isAvailable()) {
name = ComponentUtil.empty().appendSibling(name).setStyle(new Style().setColor(TextFormatting.GRAY));
}
int strWidth = this.getStringWidth(name);
this.drawString(drawContext, name, this.dim.getLimitX() - strWidth - 6, this.dim.getCenterY() - 4, 0xFFFFFFFF);
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (this.option.isAvailable() && button == 0 && this.dim.containsCursor(mouseX, mouseY)) {
cycleControl(GuiScreen.isShiftKeyDown());
this.playClickSound();
return true;
}
return false;
}
@Override
public boolean keyPressed(int keyCode) {
if (!isFocused()) return false;
if (keySelected(keyCode)) {
cycleControl(GuiScreen.isShiftKeyDown());
return true;
}
return false;
}
public void cycleControl(boolean reverse) {
int currentIndex = getCurrentIndex();
if (reverse) {
currentIndex = (currentIndex + this.allowedValues.length - 1) % this.allowedValues.length;
} else {
currentIndex = (currentIndex + 1) % this.allowedValues.length;
}
this.option.setValue(this.allowedValues[currentIndex]);
}
}
}
@@ -0,0 +1,7 @@
package org.taumc.celeritas.api.options.control;
import org.taumc.celeritas.api.options.structure.Option;
public interface OptionControlElement<T> {
Option<T> getOption();
}
@@ -0,0 +1,168 @@
package org.taumc.celeritas.api.options.control;
import net.minecraft.util.text.ITextComponent;
import org.apache.commons.lang3.Validate;
import org.embeddedt.embeddium.impl.util.collections.quadtree.Rect2i;
import org.taumc.celeritas.api.options.structure.Option;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.util.Dim2i;
public class SliderControl implements Control<Integer> {
private final Option<Integer> option;
private final int min;
private final int max;
private final int interval;
private final ControlValueFormatter mode;
public SliderControl(Option<Integer> option, int min, int max, int interval, ControlValueFormatter mode) {
Validate.isTrue(max > min, "The maximum value must be greater than the minimum value");
Validate.isTrue(interval > 0, "The slider interval must be greater than zero");
Validate.isTrue((max - min) % interval == 0, "The maximum value must be divisable by the interval");
Validate.notNull(mode, "The slider mode must not be null");
this.option = option;
this.min = min;
this.max = max;
this.interval = interval;
this.mode = mode;
}
public ControlElement<Integer> createElement(Dim2i dim) {
return new Button(this.option, dim, this.min, this.max, this.interval, this.mode);
}
public Option<Integer> getOption() {
return this.option;
}
public int getMaxWidth() {
return 130;
}
private static class Button extends ControlElement<Integer> {
private static final int THUMB_WIDTH = 2;
private static final int TRACK_HEIGHT = 1;
private final Rect2i sliderBounds;
private final ControlValueFormatter formatter;
private final int min;
private final int max;
private final int range;
private final int interval;
private double thumbPosition;
private boolean sliderHeld;
public Button(Option<Integer> option, Dim2i dim, int min, int max, int interval, ControlValueFormatter formatter) {
super(option, dim);
this.min = min;
this.max = max;
this.range = max - min;
this.interval = interval;
this.thumbPosition = this.getThumbPositionForValue(option.getValue());
this.formatter = formatter;
this.sliderBounds = new Rect2i(dim.getLimitX() - 96, dim.getCenterY() - 5, 90, 10);
this.sliderHeld = false;
}
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) {
super.render(drawContext, mouseX, mouseY, delta);
if (!this.option.isAvailable() || !this.hovered && !this.isFocused()) {
this.renderStandaloneValue(drawContext);
} else {
this.renderSlider(drawContext);
}
}
private void renderStandaloneValue(GuiGraphics drawContext) {
int sliderX = this.sliderBounds.x();
int sliderY = this.sliderBounds.y();
int sliderWidth = this.sliderBounds.width();
int sliderHeight = this.sliderBounds.height();
ITextComponent label = this.formatter.format(this.option.getValue());
int labelWidth = this.getStringWidth(label);
this.drawString(drawContext, label, sliderX + sliderWidth - labelWidth, sliderY + sliderHeight / 2 - 4, -1);
}
private void renderSlider(GuiGraphics drawContext) {
int sliderX = this.sliderBounds.x();
int sliderY = this.sliderBounds.y();
int sliderWidth = this.sliderBounds.width();
int sliderHeight = this.sliderBounds.height();
this.thumbPosition = this.getThumbPositionForValue(this.option.getValue());
double thumbOffset = Math.clamp((double)(this.getIntValue() - this.min) / (double)this.range * (double)sliderWidth, 0.0F, sliderWidth);
int thumbX = (int)((double)sliderX + thumbOffset - (double)2.0F);
int trackY = (int)((double)((float)sliderY + (float)sliderHeight / 2.0F) - (double)0.5F);
this.drawRect(drawContext, thumbX, sliderY, thumbX + 4, sliderY + sliderHeight, -1);
this.drawRect(drawContext, sliderX, trackY, sliderX + sliderWidth, trackY + 1, -1);
String label = this.formatter.format(this.getIntValue()).getFormattedText();
int labelWidth = this.font.getStringWidth(label);
this.drawString(drawContext, label, sliderX - labelWidth - 6, sliderY + sliderHeight / 2 - 4, -1);
}
public int getIntValue() {
return this.min + this.interval * (int)Math.round(this.getSnappedThumbPosition() / (double)this.interval);
}
public double getSnappedThumbPosition() {
return this.thumbPosition / ((double)1.0F / (double)this.range);
}
public double getThumbPositionForValue(int value) {
return (double)(value - this.min) * ((double)1.0F / (double)this.range);
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
this.sliderHeld = false;
if (this.option.isAvailable() && button == 0 && this.dim.containsCursor(mouseX, mouseY)) {
if (this.sliderBounds.contains((int)mouseX, (int)mouseY)) {
this.setValueFromMouse(mouseX);
this.sliderHeld = true;
}
return true;
} else {
return false;
}
}
private void setValueFromMouse(double d) {
this.setValue((d - (double)this.sliderBounds.x()) / (double)this.sliderBounds.width());
}
public void setValue(double d) {
this.thumbPosition = Math.clamp(d, 0.0F, 1.0F);
int value = this.getIntValue();
if (!this.option.getValue().equals(value)) {
this.option.setValue(value);
}
}
@Override
public boolean keyPressed(int keyCode) {
if (!this.isFocused()) {
return false;
} else if (keyCode == 203) {
this.option.setValue(Math.clamp(this.option.getValue() - this.interval, this.min, this.max));
return true;
} else if (keyCode == 205) {
this.option.setValue(Math.clamp(this.option.getValue() + this.interval, this.min, this.max));
return true;
} else {
return false;
}
}
@Override
public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) {
if (this.option.isAvailable() && button == 0) {
if (this.sliderHeld) {
this.setValueFromMouse(mouseX);
}
return true;
} else {
return false;
}
}
}
}
@@ -0,0 +1,87 @@
package org.taumc.celeritas.api.options.control;
import org.embeddedt.embeddium.impl.util.collections.quadtree.Rect2i;
import org.taumc.celeritas.api.options.structure.Option;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.gui.theme.DefaultColors;
import org.taumc.celeritas.impl.util.Dim2i;
public class TickBoxControl implements Control<Boolean> {
private final Option<Boolean> option;
public TickBoxControl(Option<Boolean> option) {
this.option = option;
}
public ControlElement<Boolean> createElement(Dim2i dim) {
return new TickBoxControlElement(this.option, dim);
}
public int getMaxWidth() {
return 30;
}
public Option<Boolean> getOption() {
return this.option;
}
private static class TickBoxControlElement extends ControlElement<Boolean> {
private final Rect2i button;
public TickBoxControlElement(Option<Boolean> option, Dim2i dim) {
super(option, dim);
this.button = new Rect2i(dim.getLimitX() - 16, dim.getCenterY() - 5, 10, 10);
}
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) {
super.render(drawContext, mouseX, mouseY, delta);
int x = this.button.x();
int y = this.button.y();
int w = x + this.button.width();
int h = y + this.button.height();
boolean enabled = this.option.isAvailable();
boolean ticked = this.option.getValue();
int color;
if (enabled) {
color = ticked ? DefaultColors.ELEMENT_ACTIVATED : 0xFFFFFFFF;
} else {
color = 0xFFAAAAAA;
}
if (ticked) {
this.drawRect(drawContext, x + 2, y + 2, w - 2, h - 2, color);
}
this.drawBorder(drawContext, x, y, w, h, color);
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (this.option.isAvailable() && button == 0 && this.dim.containsCursor(mouseX, mouseY)) {
this.toggleControl();
this.playClickSound();
return true;
} else {
return false;
}
}
@Override
public boolean keyPressed(int i) {
if (!this.isFocused()) {
return false;
} else if (keySelected(i)) {
this.toggleControl();
this.playClickSound();
return true;
} else {
return false;
}
}
public void toggleControl() {
this.option.setValue(!(Boolean)this.option.getValue());
}
}
}
@@ -0,0 +1,32 @@
package org.taumc.celeritas.api.options.named;
import java.util.Arrays;
import java.util.Comparator;
import net.minecraft.util.math.MathHelper;
public enum AttackIndicator {
OFF(0, "options.off"),
CROSSHAIR(1, "options.attack.crosshair"),
HOTBAR(2, "options.attack.hotbar");
private static final AttackIndicator[] VALUES = Arrays.stream(values()).sorted(Comparator.comparingInt(AttackIndicator::getId)).toArray(AttackIndicator[]::new);
private final int id;
private final String translationKey;
AttackIndicator(int id, String translationKey) {
this.id = id;
this.translationKey = translationKey;
}
public int getId() {
return this.id;
}
public String getTranslationKey() {
return this.translationKey;
}
public static AttackIndicator byId(int id) {
return VALUES[(int) MathHelper.positiveModulo(id, VALUES.length)];
}
}
@@ -0,0 +1,36 @@
package org.taumc.celeritas.api.options.named;
import net.minecraft.util.math.MathHelper;
import java.util.Arrays;
import java.util.Comparator;
public enum CloudStatus {
OFF(0, "options.off"),
FAST(1, "options.clouds.fast"),
FANCY(2, "options.clouds.fancy");
private static final CloudStatus[] VALUES = Arrays.stream(values())
.sorted(Comparator.comparingInt(CloudStatus::getId))
.toArray(CloudStatus[]::new);
private final int id;
private final String translationKey;
CloudStatus(int id, String translationKey) {
this.id = id;
this.translationKey = translationKey;
}
public int getId() {
return this.id;
}
public String getTranslationKey() {
return this.translationKey;
}
public static CloudStatus byId(int id) {
return VALUES[(int) MathHelper.positiveModulo(id, VALUES.length)];
}
}
@@ -0,0 +1,26 @@
package org.taumc.celeritas.api.options.named;
public enum GraphicsStatus {
FAST(false, "options.graphics.fast"),
FANCY(true, "options.graphics.fancy");
private final boolean value;
private final String translationKey;
GraphicsStatus(boolean value, String translationKey) {
this.value = value;
this.translationKey = translationKey;
}
public boolean getValue() {
return this.value;
}
public String getTranslationKey() {
return this.translationKey;
}
public static GraphicsStatus fromBoolean(boolean value) {
return value ? FANCY : FAST;
}
}
@@ -0,0 +1,36 @@
package org.taumc.celeritas.api.options.named;
import net.minecraft.util.math.MathHelper;
import java.util.Arrays;
import java.util.Comparator;
public enum ParticleMode {
ALL(0, "options.particles.all"),
DECREASED(1, "options.particles.decreased"),
MINIMAL(2, "options.particles.minimal");
private static final ParticleMode[] VALUES = Arrays.stream(values())
.sorted(Comparator.comparingInt(ParticleMode::getId))
.toArray(ParticleMode[]::new);
private final int id;
private final String translationKey;
ParticleMode(int id, String translationKey) {
this.id = id;
this.translationKey = translationKey;
}
public int getId() {
return this.id;
}
public String getTranslationKey() {
return this.translationKey;
}
public static ParticleMode byId(int id) {
return VALUES[(int) MathHelper.positiveModulo(id, VALUES.length)];
}
}
@@ -0,0 +1,36 @@
package org.taumc.celeritas.api.options.named;
import net.minecraft.util.math.MathHelper;
import java.util.Arrays;
import java.util.Comparator;
public enum SmoothLighting {
OFF(0, "options.ao.off"),
MINIMAL(1, "options.ao.min"),
MAXIMUM(2, "options.ao.max");
private static final SmoothLighting[] VALUES = Arrays.stream(values())
.sorted(Comparator.comparingInt(SmoothLighting::getId))
.toArray(SmoothLighting[]::new);
private final int id;
private final String translationKey;
SmoothLighting(int id, String translationKey) {
this.id = id;
this.translationKey = translationKey;
}
public int getId() {
return this.id;
}
public String getTranslationKey() {
return this.translationKey;
}
public static SmoothLighting byId(int id) {
return VALUES[(int) MathHelper.positiveModulo(id, VALUES.length)];
}
}
@@ -0,0 +1,28 @@
package org.taumc.celeritas.api.options.storage;
import java.util.Set;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.GameSettings;
import org.taumc.celeritas.CeleritasVintage;
import org.taumc.celeritas.api.options.structure.OptionFlag;
import org.taumc.celeritas.api.options.structure.OptionStorage;
public class MinecraftOptionsStorage implements OptionStorage<GameSettings> {
private final Minecraft client;
public MinecraftOptionsStorage() {
this.client = Minecraft.getMinecraft();
}
@Override
public GameSettings getData() {
return this.client.gameSettings;
}
@Override
public void save(Set<OptionFlag> flags) {
this.getData().saveOptions();
CeleritasVintage.logger().info("Flushed changes to Minecraft configuration");
}
}
@@ -0,0 +1,38 @@
package org.taumc.celeritas.api.options.structure;
import java.util.Collection;
import net.minecraft.util.text.ITextComponent;
import org.jetbrains.annotations.Nullable;
import org.taumc.celeritas.api.options.OptionIdentifier;
import org.taumc.celeritas.api.options.control.Control;
public interface Option<T> {
@Nullable
default OptionIdentifier<T> getId() {
return null;
}
ITextComponent getName();
ITextComponent getTooltip();
OptionImpact getImpact();
Control<T> getControl();
T getValue();
void setValue(T var1);
void reset();
OptionStorage<?> getStorage();
boolean isAvailable();
boolean hasChanged();
void applyChanges();
Collection<OptionFlag> getFlags();
}
@@ -0,0 +1,9 @@
package org.taumc.celeritas.api.options.structure;
public enum OptionFlag {
REQUIRES_RENDERER_RELOAD,
REQUIRES_RENDERER_UPDATE,
REQUIRES_ASSET_RELOAD,
REQUIRES_GAME_RESTART,
REQUIRES_SHADER_PIPELINE_RELOAD
}
@@ -0,0 +1,74 @@
package org.taumc.celeritas.api.options.structure;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import net.minecraft.util.ResourceLocation;
import org.taumc.celeritas.CeleritasVintage;
import org.taumc.celeritas.api.OptionGroupConstructionEvent;
import org.taumc.celeritas.api.options.OptionIdentifier;
public class OptionGroup {
public static final OptionIdentifier<Void> DEFAULT_ID = OptionIdentifier.create("celeritas", "empty");
private final ImmutableList<Option<?>> options;
public final OptionIdentifier<Void> id;
private OptionGroup(OptionIdentifier<Void> id, ImmutableList<Option<?>> options) {
this.id = id;
this.options = options;
}
public OptionIdentifier<Void> getId() {
return this.id;
}
public static Builder createBuilder() {
return new Builder();
}
public ImmutableList<Option<?>> getOptions() {
return this.options;
}
public static class Builder {
private final List<Option<?>> options = new ArrayList<>();
private OptionIdentifier<Void> id;
public Builder setId(ResourceLocation id) {
this.id = OptionIdentifier.create(id);
return this;
}
public Builder setId(OptionIdentifier<Void> id) {
this.id = id;
return this;
}
public Builder add(Option<?> option) {
this.options.add(option);
return this;
}
public Builder addConditionally(boolean shouldAdd, Supplier<Option<?>> option) {
if (shouldAdd) {
this.add(option.get());
}
return this;
}
public OptionGroup build() {
if (this.options.isEmpty()) {
CeleritasVintage.logger().warn("OptionGroup must contain at least one option. ignoring empty group...");
}
if (this.id == null) {
this.id = OptionGroup.DEFAULT_ID;
}
OptionGroupConstructionEvent.BUS.post(new OptionGroupConstructionEvent(this.id, this.options));
return new OptionGroup(this.id, ImmutableList.copyOf(this.options));
}
}
}
@@ -0,0 +1,25 @@
package org.taumc.celeritas.api.options.structure;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextFormatting;
import org.taumc.celeritas.impl.gui.options.TextProvider;
import org.taumc.celeritas.impl.util.ComponentUtil;
public enum OptionImpact implements TextProvider {
LOW(TextFormatting.GREEN, "sodium.option_impact.low"),
MEDIUM(TextFormatting.YELLOW, "sodium.option_impact.medium"),
HIGH(TextFormatting.GOLD, "sodium.option_impact.high"),
VARIES(TextFormatting.WHITE, "sodium.option_impact.varies");
private final ITextComponent text;
OptionImpact(TextFormatting color, String text) {
this.text = ComponentUtil.translatable(text).setStyle((new Style()).setColor(color));
}
@Override
public ITextComponent getLocalizedName() {
return this.text;
}
}
@@ -0,0 +1,220 @@
package org.taumc.celeritas.api.options.structure;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.function.BiConsumer;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import org.apache.commons.lang3.Validate;
import org.jetbrains.annotations.Nullable;
import org.taumc.celeritas.api.options.OptionIdentifier;
import org.taumc.celeritas.api.options.binding.GenericBinding;
import org.taumc.celeritas.api.options.binding.OptionBinding;
import org.taumc.celeritas.api.options.control.Control;
import org.taumc.celeritas.impl.util.ComponentUtil;
public class OptionImpl<S, T> implements Option<T> {
private final OptionStorage<S> storage;
private final OptionBinding<S, T> binding;
private final Control<T> control;
private final EnumSet<OptionFlag> flags;
private final OptionIdentifier<T> id;
private final ITextComponent name;
private final ITextComponent tooltip;
private final OptionImpact impact;
private @Nullable T modifiedValue;
private final BooleanSupplier enabled;
private OptionImpl(OptionStorage<S> storage, OptionIdentifier<T> id, ITextComponent name, ITextComponent tooltip, OptionBinding<S, T> binding, Function<OptionImpl<S, T>, Control<T>> control, EnumSet<OptionFlag> flags, OptionImpact impact, BooleanSupplier enabled) {
this.id = id;
this.storage = storage;
this.name = name;
this.tooltip = tooltip;
this.binding = binding;
this.impact = impact;
this.flags = flags;
this.control = control.apply(this);
this.enabled = enabled;
this.reset();
}
@Override
public OptionIdentifier<T> getId() {
return this.id;
}
@Override
public ITextComponent getName() {
return this.name;
}
@Override
public ITextComponent getTooltip() {
return this.tooltip;
}
@Override
public OptionImpact getImpact() {
return this.impact;
}
@Override
public Control<T> getControl() {
return this.control;
}
@Override
public T getValue() {
return this.modifiedValue != null ? this.modifiedValue : this.binding.getValue(this.storage.getData());
}
@Override
public void setValue(T value) {
this.modifiedValue = value;
}
@Override
public void reset() {
this.modifiedValue = null;
}
@Override
public OptionStorage<?> getStorage() {
return this.storage;
}
@Override
public boolean isAvailable() {
return this.enabled.getAsBoolean();
}
@Override
public boolean hasChanged() {
return this.modifiedValue != null && !this.binding.getValue(this.storage.getData()).equals(this.modifiedValue);
}
@Override
public void applyChanges() {
if (this.modifiedValue != null) {
this.binding.setValue(this.storage.getData(), this.modifiedValue);
this.modifiedValue = null;
}
}
@Override
public Collection<OptionFlag> getFlags() {
return this.flags;
}
public static <S, T> Builder<S, T> createBuilder(Class<T> type, OptionStorage<S> storage) {
return new Builder<S, T>(storage, type);
}
public static class Builder<S, T> {
private final OptionStorage<S> storage;
private final Class<T> type;
private OptionIdentifier<T> id;
private ITextComponent name;
private ITextComponent tooltip;
private OptionBinding<S, T> binding;
private Function<OptionImpl<S, T>, Control<T>> control;
private OptionImpact impact;
private final EnumSet<OptionFlag> flags = EnumSet.noneOf(OptionFlag.class);
private static final BooleanSupplier ALWAYS_ENABLED = () -> true;
private static final BooleanSupplier ALWAYS_DISABLED = () -> false;
private BooleanSupplier enabled;
private Builder(OptionStorage<S> storage, Class<T> type) {
this.enabled = ALWAYS_ENABLED;
this.storage = storage;
this.type = type;
}
public Builder<S, T> setId(ResourceLocation id) {
Validate.notNull(id, "Id must not be null");
this.id = OptionIdentifier.create(id.getNamespace(), id.getPath(), this.type);
return this;
}
public Builder<S, T> setId(OptionIdentifier<T> id) {
Validate.notNull(id, "Id must not be null");
this.id = id;
return this;
}
public Builder<S, T> setName(ITextComponent name) {
Validate.notNull(name, "Argument must not be null");
this.name = name;
return this;
}
public Builder<S, T> setTooltip(ITextComponent tooltip) {
Validate.notNull(tooltip, "Argument must not be null");
this.tooltip = tooltip;
return this;
}
public Builder<S, T> setBinding(BiConsumer<S, T> setter, Function<S, T> getter) {
Validate.notNull(setter, "Setter must not be null");
Validate.notNull(getter, "Getter must not be null");
this.binding = new GenericBinding(setter, getter);
return this;
}
public Builder<S, T> setBinding(OptionBinding<S, T> binding) {
Validate.notNull(binding, "Argument must not be null");
this.binding = binding;
return this;
}
public Builder<S, T> setControl(Function<OptionImpl<S, T>, Control<T>> control) {
Validate.notNull(control, "Argument must not be null");
this.control = control;
return this;
}
public Builder<S, T> setImpact(OptionImpact impact) {
this.impact = impact;
return this;
}
public Builder<S, T> setEnabledPredicate(BooleanSupplier value) {
this.enabled = value;
return this;
}
public Builder<S, T> setEnabled(boolean value) {
this.setEnabledPredicate(value ? ALWAYS_ENABLED : ALWAYS_DISABLED);
return this;
}
public Builder<S, T> setFlags(OptionFlag... flags) {
Collections.addAll(this.flags, flags);
return this;
}
public OptionImpl<S, T> build() {
if (this.id == null) {
this.id = (OptionIdentifier<T>) OptionIdentifier.EMPTY;
} else {
if (this.name == null) {
this.name = ComponentUtil.translatable(this.id.getModId() + ".options." + this.id.getPath() + ".name");
}
if (this.tooltip == null) {
this.tooltip = ComponentUtil.translatable(this.id.getModId() + ".options." + this.id.getPath() + ".tooltip");
}
}
Validate.notNull(this.name, "Name must be specified or inferred from a specified ID");
Validate.notNull(this.tooltip, "Tooltip must be specified or inferred from a specified ID");
Validate.notNull(this.binding, "Option binding must be specified");
Validate.notNull(this.control, "Control must be specified");
return new OptionImpl<S, T>(this.storage, this.id, this.name, this.tooltip, this.binding, this.control, this.flags, this.impact, this.enabled);
}
}
}
@@ -0,0 +1,91 @@
package org.taumc.celeritas.api.options.structure;
import com.google.common.collect.ImmutableList;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentTranslation;
import org.taumc.celeritas.CeleritasVintage;
import org.taumc.celeritas.api.OptionPageConstructionEvent;
import org.taumc.celeritas.api.options.OptionIdentifier;
import java.util.List;
public class OptionPage {
public static final OptionIdentifier<Void> DEFAULT_ID = OptionIdentifier.create(CeleritasVintage.MODID, "empty");
private final OptionIdentifier<Void> id;
private final ITextComponent name;
private final ImmutableList<OptionGroup> groups;
private final ImmutableList<Option<?>> options;
private static String findKey(ITextComponent name) {
if(name instanceof TextComponentTranslation component) {
if (component.getSiblings().isEmpty()) {
return component.getKey();
}
}
return null;
}
private static OptionIdentifier<Void> tryMakeId(ITextComponent name) {
OptionIdentifier<Void> id = null;
String key = findKey(name);
if (key != null) {
// Detect our own tabs
id = switch(key) {
case "stat.generalButton" -> StandardOptions.Pages.GENERAL;
case "sodium.options.pages.quality" -> StandardOptions.Pages.QUALITY;
case "sodium.options.pages.advanced" -> StandardOptions.Pages.ADVANCED;
case "sodium.options.pages.performance" -> StandardOptions.Pages.PERFORMANCE;
default -> null;
};
}
if(id != null) {
return id;
} else {
throw new IllegalStateException("ID must be provided for option page");
}
}
@Deprecated
public OptionPage(ITextComponent name, ImmutableList<OptionGroup> groups) {
this(tryMakeId(name), name, groups);
}
public OptionPage(OptionIdentifier<Void> id, ITextComponent name, ImmutableList<OptionGroup> groups) {
this.id = id;
this.name = name;
this.groups = collectExtraGroups(groups);
ImmutableList.Builder<Option<?>> builder = ImmutableList.builder();
for (OptionGroup group : this.groups) {
builder.addAll(group.getOptions());
}
this.options = builder.build();
}
private ImmutableList<OptionGroup> collectExtraGroups(ImmutableList<OptionGroup> groups) {
OptionPageConstructionEvent event = new OptionPageConstructionEvent(this.id, this.name);
OptionPageConstructionEvent.BUS.post(event);
List<OptionGroup> extraGroups = event.getAdditionalGroups();
return extraGroups.isEmpty() ? groups : ImmutableList.<OptionGroup>builder().addAll(groups).addAll(extraGroups).build();
}
public OptionIdentifier<Void> getId() {
return id;
}
public ImmutableList<OptionGroup> getGroups() {
return this.groups;
}
public ImmutableList<Option<?>> getOptions() {
return this.options;
}
public ITextComponent getName() {
return this.name;
}
}
@@ -0,0 +1,14 @@
package org.taumc.celeritas.api.options.structure;
import java.util.Set;
public interface OptionStorage<T> {
T getData();
default void save() {
}
default void save(Set<OptionFlag> flags) {
this.save();
}
}
@@ -0,0 +1,71 @@
package org.taumc.celeritas.api.options.structure;
import net.minecraft.util.ResourceLocation;
import org.taumc.celeritas.api.options.OptionIdentifier;
import org.taumc.celeritas.impl.util.ResourceLocationUtil;
public final class StandardOptions {
public static class Group {
public static final ResourceLocation RENDERING = ResourceLocationUtil.make("minecraft", "rendering");
public static final ResourceLocation WINDOW = ResourceLocationUtil.make("minecraft", "window");
public static final ResourceLocation INDICATORS = ResourceLocationUtil.make("minecraft", "indicators");
public static final ResourceLocation GRAPHICS = ResourceLocationUtil.make("minecraft", "graphics");
public static final ResourceLocation MIPMAPS = ResourceLocationUtil.make("minecraft", "mipmaps");
public static final ResourceLocation DETAILS = ResourceLocationUtil.make("minecraft", "details");
public static final ResourceLocation CHUNK_UPDATES = ResourceLocationUtil.make("celeritas", "chunk_updates");
public static final ResourceLocation RENDERING_CULLING = ResourceLocationUtil.make("celeritas", "rendering_culling");
public static final ResourceLocation CPU_SAVING = ResourceLocationUtil.make("celeritas", "cpu_saving");
public static final ResourceLocation SORTING = ResourceLocationUtil.make("celeritas", "sorting");
public static final ResourceLocation LIGHTING = ResourceLocationUtil.make("celeritas", "lighting");
}
public static class Pages {
public static final OptionIdentifier<Void> GENERAL = OptionIdentifier.create("celeritas", "general");
public static final OptionIdentifier<Void> QUALITY = OptionIdentifier.create("celeritas", "quality");
public static final OptionIdentifier<Void> PERFORMANCE = OptionIdentifier.create("celeritas", "performance");
public static final OptionIdentifier<Void> ADVANCED = OptionIdentifier.create("celeritas", "advanced");
public static final OptionIdentifier<Void> SHADERS = OptionIdentifier.create("celeritas", "shaders");
}
public static class Option {
public static final ResourceLocation RENDER_DISTANCE = ResourceLocationUtil.make("minecraft", "render_distance");
public static final ResourceLocation SIMULATION_DISTANCE = ResourceLocationUtil.make("minecraft", "simulation_distance");
public static final ResourceLocation BRIGHTNESS = ResourceLocationUtil.make("minecraft", "brightness");
public static final ResourceLocation GUI_SCALE = ResourceLocationUtil.make("minecraft", "gui_scale");
public static final ResourceLocation FULLSCREEN = ResourceLocationUtil.make("minecraft", "fullscreen");
public static final ResourceLocation FULLSCREEN_RESOLUTION = ResourceLocationUtil.make("minecraft", "fullscreen_resolution");
public static final ResourceLocation VSYNC = ResourceLocationUtil.make("minecraft", "vsync");
public static final ResourceLocation MAX_FRAMERATE = ResourceLocationUtil.make("minecraft", "max_frame_rate");
public static final ResourceLocation VIEW_BOBBING = ResourceLocationUtil.make("minecraft", "view_bobbing");
public static final ResourceLocation INACTIVITY_FPS_LIMIT = ResourceLocationUtil.make("minecraft", "inactivity_fps_limit");
public static final ResourceLocation ATTACK_INDICATOR = ResourceLocationUtil.make("minecraft", "attack_indicator");
public static final ResourceLocation AUTOSAVE_INDICATOR = ResourceLocationUtil.make("minecraft", "autosave_indicator");
public static final ResourceLocation GRAPHICS_MODE = ResourceLocationUtil.make("minecraft", "graphics_mode");
public static final ResourceLocation CLOUDS = ResourceLocationUtil.make("minecraft", "clouds");
public static final ResourceLocation WEATHER = ResourceLocationUtil.make("minecraft", "weather");
public static final ResourceLocation LEAVES = ResourceLocationUtil.make("minecraft", "leaves");
public static final ResourceLocation PARTICLES = ResourceLocationUtil.make("minecraft", "particles");
public static final ResourceLocation SMOOTH_LIGHT = ResourceLocationUtil.make("minecraft", "smooth_lighting");
public static final ResourceLocation BIOME_BLEND = ResourceLocationUtil.make("minecraft", "biome_blend");
public static final ResourceLocation ENTITY_DISTANCE = ResourceLocationUtil.make("minecraft", "entity_distance");
public static final ResourceLocation ENTITY_SHADOWS = ResourceLocationUtil.make("minecraft", "entity_shadows");
public static final ResourceLocation VIGNETTE = ResourceLocationUtil.make("minecraft", "vignette");
public static final ResourceLocation MIPMAP_LEVEL = ResourceLocationUtil.make("minecraft", "mipmap_levels");
public static final ResourceLocation CHUNK_UPDATE_THREADS = ResourceLocationUtil.make("celeritas", "chunk_update_threads");
public static final ResourceLocation DEFFER_CHUNK_UPDATES = ResourceLocationUtil.make("celeritas", "defer_chunk_updates");
public static final ResourceLocation BLOCK_FACE_CULLING = ResourceLocationUtil.make("celeritas", "block_face_culling");
public static final ResourceLocation COMPACT_VERTEX_FORMAT = ResourceLocationUtil.make("celeritas", "compact_vertex_format");
public static final ResourceLocation FOG_OCCLUSION = ResourceLocationUtil.make("celeritas", "fog_occlusion");
public static final ResourceLocation ENTITY_CULLING = ResourceLocationUtil.make("celeritas", "entity_culling");
public static final ResourceLocation ANIMATE_VISIBLE_TEXTURES = ResourceLocationUtil.make("celeritas", "animate_only_visible_textures");
public static final ResourceLocation NO_ERROR_CONTEXT = ResourceLocationUtil.make("celeritas", "no_error_context");
public static final ResourceLocation PERSISTENT_MAPPING = ResourceLocationUtil.make("celeritas", "persistent_mapping");
public static final ResourceLocation CPU_FRAMES_AHEAD = ResourceLocationUtil.make("celeritas", "cpu_render_ahead_limit");
public static final ResourceLocation TRANSLUCENT_FACE_SORTING = ResourceLocationUtil.make("celeritas", "translucent_face_sorting");
public static final ResourceLocation USE_QUAD_NORMALS_FOR_LIGHTING = ResourceLocationUtil.make("celeritas", "use_quad_normals_for_lighting");
public static final ResourceLocation RENDER_PASS_OPTIMIZATION = ResourceLocationUtil.make("celeritas", "render_pass_optimization");
public static final ResourceLocation RENDER_PASS_CONSOLIDATION = ResourceLocationUtil.make("celeritas", "render_pass_consolidation");
public static final ResourceLocation USE_FASTER_CLOUDS = ResourceLocationUtil.make("celeritas", "use_faster_clouds");
public static final ResourceLocation ASYNC_GRAPH_SEARCH = ResourceLocationUtil.make("celeritas", "async_graph_search");
}
}
@@ -0,0 +1,66 @@
package org.taumc.celeritas.impl.compat.modernui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import org.taumc.celeritas.CeleritasVintage;
import java.lang.reflect.Method;
import java.util.stream.Stream;
/**
* Ugly hack to get around Modern UI overwriting calculateScaleFactor and not conforming to vanilla standards
* by returning the max size when scale = 0.
*/
public class MuiGuiScaleHook {
private static final Method calcGuiScalesMethod;
static {
calcGuiScalesMethod = Stream.of(
"icyllis.modernui.forge.MForgeCompat",
"icyllis.modernui.forge.MuiForgeApi",
"icyllis.modernui.mc.forge.MuiForgeApi",
"icyllis.modernui.mc.MuiModApi"
).flatMap(clzName -> {
try {
return Stream.of(Class.forName(clzName));
} catch (Throwable e) {
return Stream.of();
}
}).flatMap(clz -> {
try {
Method m = clz.getDeclaredMethod("calcGuiScales");
m.setAccessible(true);
return Stream.of(m);
} catch (Throwable e) {
return Stream.of();
}
}).findFirst().orElse(null);
if (calcGuiScalesMethod != null)
CeleritasVintage.logger().info("Found ModernUI GUI scale hook");
}
public static int getMaxGuiScale() {
if (calcGuiScalesMethod != null) {
try {
return (int) calcGuiScalesMethod.invoke(null) & 0xf;
} catch (Throwable e) {
e.printStackTrace();
}
}
boolean forceUnicode = Minecraft.getMinecraft().gameSettings.forceUnicodeFont;
return calculateScale(0, forceUnicode);
}
public static int calculateScale(int guiScale, boolean forceUnicode) {
int i;
for (i = 1; i != guiScale && i < Minecraft.getMinecraft().getFramebuffer().framebufferWidth && i < Minecraft.getMinecraft().getFramebuffer().framebufferHeight && Minecraft.getMinecraft().getFramebuffer().framebufferWidth / (i + 1) >= 320 && Minecraft.getMinecraft().getFramebuffer().framebufferHeight / (i + 1) >= 240; ++i) {
}
if (forceUnicode && i % 2 != 0) {
++i;
}
return i;
}
}
@@ -0,0 +1,34 @@
package org.taumc.celeritas.impl.config;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.taumc.celeritas.impl.util.PlatformUtil;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ConfigMigrator {
public static Logger LOGGER = LogManager.getLogger("Embeddium");
/**
* Tries to migrate the equivalent config file from Rubidium to the Embeddium name if possible.
*/
public static Path handleConfigMigration(String fileName) {
Path mainPath = PlatformUtil.getConfigDir().toPath().resolve(fileName);
try {
if(Files.notExists(mainPath)) {
String legacyName = fileName.replace("assets/celeritas", "rubidium");
Path legacyPath = PlatformUtil.getConfigDir().toPath().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;
}
}
@@ -0,0 +1,377 @@
package org.taumc.celeritas.impl.gui;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiVideoSettings;
import net.minecraft.util.text.ITextComponent;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.taumc.celeritas.api.OptionGUIConstructionEvent;
import org.taumc.celeritas.api.options.structure.Option;
import org.taumc.celeritas.api.options.structure.OptionFlag;
import org.taumc.celeritas.api.options.structure.OptionGroup;
import org.taumc.celeritas.api.options.structure.OptionPage;
import org.taumc.celeritas.api.options.structure.OptionStorage;
import org.taumc.celeritas.impl.gui.compat.Element;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.gui.frame.AbstractFrame;
import org.taumc.celeritas.impl.gui.frame.BasicFrame;
import org.taumc.celeritas.impl.gui.frame.OptionPageFrame;
import org.taumc.celeritas.impl.gui.frame.components.SearchTextFieldComponent;
import org.taumc.celeritas.impl.gui.frame.components.SearchTextFieldModel;
import org.taumc.celeritas.impl.gui.frame.tab.Tab;
import org.taumc.celeritas.impl.gui.frame.tab.TabFrame;
import org.taumc.celeritas.impl.gui.widgets.FlatButtonWidget;
import org.taumc.celeritas.impl.util.ComponentUtil;
import org.taumc.celeritas.impl.util.Dim2i;
public class CeleritasVideoOptionsScreen extends GuiScreen {
private static final AtomicReference<ITextComponent> tabFrameSelectedTab = new AtomicReference<>(null);
private final AtomicReference<Integer> tabFrameScrollBarOffset = new AtomicReference<>(0);
private final AtomicReference<Integer> optionPageScrollBarOffset = new AtomicReference<>(0);
public final GuiScreen prevScreen;
private final List<OptionPage> pages = new ArrayList<>();
private AbstractFrame frame;
private FlatButtonWidget applyButton, closeButton, undoButton;
private boolean hasPendingChanges;
private SearchTextFieldComponent searchTextField;
private final SearchTextFieldModel searchTextModel;
private double lastMouseX = -1;
private double lastMouseY = -1;
public CeleritasVideoOptionsScreen(GuiScreen prev) {
this.prevScreen = prev;
this.pages.add(SodiumGameOptionPages.general());
this.pages.add(SodiumGameOptionPages.quality());
this.pages.add(SodiumGameOptionPages.performance());
this.pages.add(SodiumGameOptionPages.advanced());
OptionGUIConstructionEvent.BUS.post(new OptionGUIConstructionEvent(this.pages));
this.searchTextModel = new SearchTextFieldModel(this.pages, this);
}
public void rebuildUI() {
boolean wasSearchFocused = this.searchTextField.isFocused();
this.initGui();
if (wasSearchFocused) {
this.searchTextField.setFocused(true);
}
}
@Override
public void initGui() {
this.frame = this.parentFrameBuilder().build();
}
private static final float ASPECT_RATIO = 5f / 4f;
private static final int MINIMUM_WIDTH = 550;
protected BasicFrame.Builder parentFrameBuilder() {
int newWidth = this.width;
if (newWidth > MINIMUM_WIDTH && (float) this.width / (float) this.height > ASPECT_RATIO) {
newWidth = Math.max(MINIMUM_WIDTH, (int) (this.height * ASPECT_RATIO));
}
Dim2i basicFrameDim = new Dim2i((this.width - newWidth) / 2, 0, newWidth, this.height);
Dim2i tabFrameDim = new Dim2i(basicFrameDim.x() + basicFrameDim.width() / 20 / 2, basicFrameDim.y() + basicFrameDim.height() / 4 / 2, basicFrameDim.width() - basicFrameDim.width() / 20, basicFrameDim.height() / 4 * 3);
Dim2i undoButtonDim = new Dim2i(tabFrameDim.getLimitX() - 203, tabFrameDim.getLimitY() + 5, 65, 20);
Dim2i applyButtonDim = new Dim2i(tabFrameDim.getLimitX() - 134, tabFrameDim.getLimitY() + 5, 65, 20);
Dim2i closeButtonDim = new Dim2i(tabFrameDim.getLimitX() - 65, tabFrameDim.getLimitY() + 5, 65, 20);
this.undoButton = new FlatButtonWidget(undoButtonDim, ComponentUtil.translatable("sodium.options.buttons.undo"), this::undoChanges);
this.applyButton = new FlatButtonWidget(applyButtonDim, ComponentUtil.translatable("sodium.options.buttons.apply"), this::applyChanges);
this.closeButton = new FlatButtonWidget(closeButtonDim, ComponentUtil.translatable("gui.done"), this::onClose);
Dim2i searchTextFieldDim = new Dim2i(tabFrameDim.x(), tabFrameDim.y() - 26, tabFrameDim.width(), 20);
BasicFrame.Builder basicFrameBuilder = this.parentBasicFrameBuilder(basicFrameDim, tabFrameDim);
this.searchTextField = new SearchTextFieldComponent(searchTextFieldDim, this.pages, this.searchTextModel);
basicFrameBuilder.addChild((dim) -> this.searchTextField);
return basicFrameBuilder;
}
private boolean canShowPage(OptionPage page) {
if (page.getGroups().isEmpty()) {
return false;
}
// Check if any options on this page are visible
var predicate = searchTextModel.getOptionPredicate();
for (OptionGroup group : page.getGroups()) {
for (Option<?> option : group.getOptions()) {
if (predicate.test(option)) {
return true;
}
}
}
return false;
}
private AbstractFrame createTabFrame(Dim2i tabFrameDim) {
// TabFrame will automatically expand its height to fit all tabs, so the scrollable frame can handle it
return TabFrame.createBuilder()
.setDimension(tabFrameDim)
.shouldRenderOutline(false)
.setTabSectionScrollBarOffset(tabFrameScrollBarOffset)
.setTabSectionSelectedTab(tabFrameSelectedTab)
.addTabs(tabs -> this.pages
.stream()
.filter(this::canShowPage)
.forEach(page -> tabs.put(page.getId().getModId(), Tab.createBuilder().from(page, searchTextModel.getOptionPredicate(), optionPageScrollBarOffset)))
)
.onSetTab(() -> {
optionPageScrollBarOffset.set(0);
})
.build();
}
public BasicFrame.Builder parentBasicFrameBuilder(Dim2i parentBasicFrameDim, Dim2i tabFrameDim) {
return BasicFrame.createBuilder()
.setDimension(parentBasicFrameDim)
.shouldRenderOutline(false)
.addChild(parentDim -> this.createTabFrame(tabFrameDim))
.addChild(dim -> this.undoButton)
.addChild(dim -> this.applyButton)
.addChild(dim -> this.closeButton);
}
@Override
public void drawScreen(int mouseX, int mouseY, float delta) {
this.drawDefaultBackground();
this.updateControls();
this.frame.render(new GuiGraphics(), mouseX, mouseY, delta);
}
private void updateControls() {
boolean hasChanges = this.getAllOptions().anyMatch(Option::hasChanged);
this.applyButton.setEnabled(hasChanges);
this.undoButton.setVisible(hasChanges);
this.closeButton.setEnabled(!hasChanges);
this.hasPendingChanges = hasChanges;
}
private Stream<Option<?>> getAllOptions() {
return this.pages.stream().flatMap((s) -> s.getOptions().stream());
}
private void applyChanges() {
HashSet<OptionStorage<?>> dirtyStorages = new HashSet<>();
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_GAME_RESTART)) {
//Console.instance().logMessage(MessageLevel.WARN, ComponentUtil.translatable("sodium.console.game_restart", new Object[0]), (double)10.0F);
}
for (OptionStorage<?> storage : dirtyStorages) {
storage.save(flags);
}
Minecraft client = Minecraft.getMinecraft();
if (client.world != null) {
if (flags.contains(OptionFlag.REQUIRES_RENDERER_RELOAD)) {
client.renderGlobal.loadRenderers();
}
if (flags.contains(OptionFlag.REQUIRES_ASSET_RELOAD)) {
client.getTextureMapBlocks().setMipmapLevels(this.mc.gameSettings.mipmapLevels);
client.refreshResources();
}
}
}
private void undoChanges() {
this.getAllOptions().forEach(Option::reset);
}
public boolean shouldCloseOnEsc() {
return !this.hasPendingChanges;
}
public void onClose() {
this.mc.displayGuiScreen(this.prevScreen);
super.onGuiClosed();
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
super.mouseClicked(mouseX, mouseY, mouseButton);
class RecursiveProcessor {
void process(Element element, boolean applyOffset, int mouseX, int mouseY, int mouseButton) {
int localMouseY = applyOffset ? mouseY + optionPageScrollBarOffset.get() : mouseY;
element.mouseClicked(mouseX, localMouseY, mouseButton);
boolean nextApplyOffset;
if (element instanceof TabFrame) {
nextApplyOffset = false;
} else if (element instanceof OptionPageFrame) {
nextApplyOffset = true;
} else {
nextApplyOffset = applyOffset;
}
new ArrayList<>(element.children()).forEach(child -> process(child, nextApplyOffset, mouseX, mouseY, mouseButton));
}
}
new RecursiveProcessor().process(this.frame, false, mouseX, mouseY, mouseButton);
}
@Override
protected void mouseReleased(int mouseX, int mouseY, int mouseButton) {
super.mouseReleased(mouseX, mouseY, mouseButton);
class RecursiveProcessor {
void process(Element element, boolean applyOffset, int mouseX, int mouseY, int mouseButton) {
int localMouseY = applyOffset ? mouseY + optionPageScrollBarOffset.get() : mouseY;
element.mouseReleased(mouseX, localMouseY, mouseButton);
boolean nextApplyOffset;
if (element instanceof TabFrame) {
nextApplyOffset = false;
} else if (element instanceof OptionPageFrame) {
nextApplyOffset = true;
} else {
nextApplyOffset = applyOffset;
}
new ArrayList<>(element.children()).forEach(child ->
process(child, nextApplyOffset, mouseX, mouseY, mouseButton));
}
}
new RecursiveProcessor().process(this.frame, false, mouseX, mouseY, mouseButton);
}
@Override
protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) {
super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick);
double dx = lastMouseX >= 0 ? mouseX - lastMouseX : 0;
double dy = lastMouseY >= 0 ? mouseY - lastMouseY : 0;
class RecursiveProcessor {
void process(Element element, boolean applyOffset, int mouseX, int mouseY, int mouseButton, double dx, double dy) {
int localMouseY = applyOffset ? mouseY + optionPageScrollBarOffset.get() : mouseY;
element.mouseDragged(mouseX, localMouseY, mouseButton, dx, dy);
boolean nextApplyOffset;
if (element instanceof TabFrame) {
nextApplyOffset = false;
} else if (element instanceof OptionPageFrame) {
nextApplyOffset = true;
} else {
nextApplyOffset = applyOffset;
}
new ArrayList<>(element.children()).forEach(child ->
process(child, nextApplyOffset, mouseX, mouseY, mouseButton, dx, dy));
}
}
new RecursiveProcessor().process(this.frame, false, mouseX, mouseY, clickedMouseButton, dx, dy);
lastMouseX = mouseX;
lastMouseY = mouseY;
}
@Override
public void keyTyped(char typedChar, int keyCode) throws IOException {
super.keyTyped(typedChar, keyCode);
if (keyCode != Keyboard.KEY_ESCAPE || this.shouldCloseOnEsc()) {
if (keyCode == Keyboard.KEY_ESCAPE) {
this.onClose();
} else if (keyCode == Keyboard.KEY_P && isShiftKeyDown()) {
this.mc.displayGuiScreen(new GuiVideoSettings(this.prevScreen, this.mc.gameSettings));
}
}
class RecursiveProcessor {
void process(Element element) {
List<Element> children = new ArrayList<>(element.children());
children.forEach(child -> {
child.keyPressed(keyCode);
child.charTyped(typedChar);
process(child);
});
}
}
new RecursiveProcessor().process(this.frame);
}
@Override
public void handleMouseInput() throws IOException {
super.handleMouseInput();
int dWheel = Mouse.getEventDWheel();
if (dWheel != 0) {
int mouseX = Mouse.getEventX() * this.width / this.mc.displayWidth;
int mouseY = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1;
double scrollDelta = dWheel > 0 ? 1 : -1;
class RecursiveProcessor {
void process(Element element, int mouseX, int mouseY, double scrollDelta) {
int adjustedMouseY = mouseY + optionPageScrollBarOffset.get();
element.mouseScrolled(mouseX, adjustedMouseY, scrollDelta);
new ArrayList<>(element.children()).forEach(child ->
process(child, mouseX, mouseY, scrollDelta));
}
}
new RecursiveProcessor().process(this.frame, mouseX, mouseY, scrollDelta);
}
}
@Override
public void onResize(Minecraft mcIn, int w, int h){
super.onResize(mcIn, w, h);
optionPageScrollBarOffset.set(0);
rebuildUI();
}
}
@@ -0,0 +1,396 @@
package org.taumc.celeritas.impl.gui;
import com.google.common.collect.ImmutableList;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.util.text.ITextComponent;
import org.embeddedt.embeddium.impl.gl.arena.staging.MappedStagingBuffer;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.render.chunk.compile.executor.ChunkBuilder;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode;
import org.lwjgl.opengl.Display;
import org.taumc.celeritas.api.options.named.*;
import org.taumc.celeritas.api.options.structure.*;
import org.taumc.celeritas.impl.compat.modernui.MuiGuiScaleHook;
import org.taumc.celeritas.api.options.control.ControlValueFormatter;
import org.taumc.celeritas.api.options.control.CyclingControl;
import org.taumc.celeritas.api.options.control.SliderControl;
import org.taumc.celeritas.api.options.control.TickBoxControl;
import org.taumc.celeritas.api.options.storage.MinecraftOptionsStorage;
import org.taumc.celeritas.impl.gui.options.storage.SodiumOptionsStorage;
import net.minecraft.client.*;
import org.taumc.celeritas.impl.util.ComponentUtil;
import java.util.ArrayList;
import java.util.List;
public class SodiumGameOptionPages {
private static final SodiumOptionsStorage sodiumOpts = new SodiumOptionsStorage();
private static final MinecraftOptionsStorage vanillaOpts = new MinecraftOptionsStorage();
private static int computeMaxRangeForRenderDistance(@SuppressWarnings("SameParameterValue") int injectedRenderDistance) {
return injectedRenderDistance;
}
public static OptionPage general() {
List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.setId(StandardOptions.Group.RENDERING)
.add(OptionImpl.createBuilder(int.class, vanillaOpts)
.setId(StandardOptions.Option.RENDER_DISTANCE)
.setName(ComponentUtil.literal(I18n.format("options.renderDistance")))
.setTooltip(ComponentUtil.translatable("sodium.options.view_distance.tooltip"))
.setControl(option -> new SliderControl(option, 2, computeMaxRangeForRenderDistance(32), 1, ControlValueFormatter.translateVariable("options.chunks")))
.setBinding((options, value) -> options.renderDistanceChunks = value, options -> options.renderDistanceChunks)
.setImpact(OptionImpact.HIGH)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(int.class, vanillaOpts)
.setId(StandardOptions.Option.BRIGHTNESS)
.setName(ComponentUtil.translatable("options.gamma"))
.setTooltip(ComponentUtil.translatable("sodium.options.brightness.tooltip"))
.setControl(opt -> new SliderControl(opt, 0, 100, 1, ControlValueFormatter.brightness()))
.setBinding((opts, value) -> opts.gammaSetting = (float) (value * 0.01D), (opts) -> (int) (opts.gammaSetting / 0.01D))
.build())
.build());
groups.add(OptionGroup.createBuilder()
.setId(StandardOptions.Group.WINDOW)
.add(OptionImpl.createBuilder(int.class, vanillaOpts)
.setId(StandardOptions.Option.GUI_SCALE)
.setName(ComponentUtil.translatable("options.guiScale"))
.setTooltip(ComponentUtil.translatable("sodium.options.gui_scale.tooltip"))
.setControl(option -> new SliderControl(option, 0, MuiGuiScaleHook.getMaxGuiScale(), 1, ControlValueFormatter.guiScale()))
.setBinding((opts, value) -> {
opts.guiScale = value;
Minecraft mc = Minecraft.getMinecraft();
mc.resize(mc.displayWidth, mc.displayHeight);
}, opts -> opts.guiScale)
.build())
.add(OptionImpl.createBuilder(boolean.class, vanillaOpts)
.setId(StandardOptions.Option.FULLSCREEN)
.setName(ComponentUtil.translatable("options.fullscreen"))
.setTooltip(ComponentUtil.translatable("sodium.options.fullscreen.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> {
opts.fullScreen = value;
Minecraft client = Minecraft.getMinecraft();
if (client.isFullScreen() != opts.fullScreen) {
client.toggleFullscreen();
// The client might not be able to enter full-screen mode
opts.fullScreen = client.isFullScreen();
}
}, (opts) -> opts.fullScreen)
.build())
.add(OptionImpl.createBuilder(boolean.class, vanillaOpts)
.setId(StandardOptions.Option.VSYNC)
.setName(ComponentUtil.translatable("options.vsync"))
.setTooltip(ComponentUtil.translatable("sodium.options.v_sync.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> {
opts.enableVsync = value;
Display.setVSyncEnabled(opts.enableVsync);
}, opts -> opts.enableVsync)
.setImpact(OptionImpact.VARIES)
.build())
.add(OptionImpl.createBuilder(int.class, vanillaOpts)
.setId(StandardOptions.Option.MAX_FRAMERATE)
.setName(ComponentUtil.translatable("options.framerateLimit"))
.setTooltip(ComponentUtil.translatable("sodium.options.fps_limit.tooltip"))
.setControl(option -> new SliderControl(option, 10, 260, 10, ControlValueFormatter.fpsLimit()))
.setBinding((opts, value) -> opts.limitFramerate = value, opts -> opts.limitFramerate)
.build())
.build());
groups.add(OptionGroup.createBuilder()
.setId(StandardOptions.Group.INDICATORS)
.add(OptionImpl.createBuilder(boolean.class, vanillaOpts)
.setId(StandardOptions.Option.VIEW_BOBBING)
.setName(ComponentUtil.translatable("options.viewBobbing"))
.setTooltip(ComponentUtil.translatable("sodium.options.view_bobbing.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.viewBobbing = value, opts -> opts.viewBobbing)
.build())
.add(OptionImpl.createBuilder(AttackIndicator.class, vanillaOpts)
.setId(StandardOptions.Option.ATTACK_INDICATOR)
.setName(ComponentUtil.translatable("options.attackIndicator"))
.setTooltip(ComponentUtil.translatable("sodium.options.attack_indicator.tooltip"))
.setControl(opts -> new CyclingControl<>(opts, AttackIndicator.class, new ITextComponent[] {
ComponentUtil.translatable(AttackIndicator.OFF.getTranslationKey()),
ComponentUtil.translatable(AttackIndicator.CROSSHAIR.getTranslationKey()),
ComponentUtil.translatable(AttackIndicator.HOTBAR.getTranslationKey()) }))
.setBinding((opts, value) -> opts.attackIndicator = value.getId(), (opts) -> AttackIndicator.byId(opts.attackIndicator))
.build())
.build());
return new OptionPage(ComponentUtil.translatable("stat.generalButton"), ImmutableList.copyOf(groups));
}
public static OptionPage quality() {
List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.setId(StandardOptions.Group.GRAPHICS)
.add(OptionImpl.createBuilder(GraphicsStatus.class, vanillaOpts)
.setId(StandardOptions.Option.GRAPHICS_MODE)
.setName(ComponentUtil.translatable("options.graphics"))
.setTooltip(ComponentUtil.translatable("sodium.options.graphics_quality.tooltip"))
.setControl(option -> new CyclingControl<>(option, GraphicsStatus.class, new ITextComponent[] {
ComponentUtil.translatable(GraphicsStatus.FAST.getTranslationKey()),
ComponentUtil.translatable(GraphicsStatus.FANCY.getTranslationKey()) }))
.setBinding((opts, value) -> opts.fancyGraphics = value.getValue(), opts -> GraphicsStatus.fromBoolean(opts.fancyGraphics))
.setImpact(OptionImpact.HIGH)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.build());
groups.add(OptionGroup.createBuilder()
.setId(StandardOptions.Group.DETAILS)
.add(OptionImpl.createBuilder(CloudStatus.class, vanillaOpts)
.setId(StandardOptions.Option.CLOUDS)
.setName(ComponentUtil.translatable("options.renderClouds"))
.setTooltip(ComponentUtil.translatable("sodium.options.clouds_quality.tooltip"))
.setControl(option -> new CyclingControl<>(option, CloudStatus.class, new ITextComponent[] {
ComponentUtil.translatable(CloudStatus.OFF.getTranslationKey()),
ComponentUtil.translatable(CloudStatus.FAST.getTranslationKey()),
ComponentUtil.translatable(CloudStatus.FANCY.getTranslationKey()) }))
.setBinding((opts, value) -> {
opts.clouds = value.getId();
}, opts -> {
return CloudStatus.byId(opts.clouds);
})
.setImpact(OptionImpact.LOW)
.build())
.add(OptionImpl.createBuilder(SodiumGameOptions.GraphicsQuality.class, sodiumOpts)
.setId(StandardOptions.Option.WEATHER)
.setName(ComponentUtil.translatable("soundCategory.weather"))
.setTooltip(ComponentUtil.translatable("sodium.options.weather_quality.tooltip"))
.setControl(option -> new CyclingControl<>(option, SodiumGameOptions.GraphicsQuality.class))
.setBinding((opts, value) -> opts.quality.weatherQuality = value, opts -> opts.quality.weatherQuality)
.setImpact(OptionImpact.MEDIUM)
.build())
.add(OptionImpl.createBuilder(SodiumGameOptions.GraphicsQuality.class, sodiumOpts)
.setId(StandardOptions.Option.LEAVES)
.setName(ComponentUtil.translatable("sodium.options.leaves_quality.name"))
.setTooltip(ComponentUtil.translatable("sodium.options.leaves_quality.tooltip"))
.setControl(option -> new CyclingControl<>(option, SodiumGameOptions.GraphicsQuality.class))
.setBinding((opts, value) -> opts.quality.leavesQuality = value, opts -> opts.quality.leavesQuality)
.setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(ParticleMode.class, vanillaOpts)
.setId(StandardOptions.Option.PARTICLES)
.setName(ComponentUtil.translatable("options.particles"))
.setTooltip(ComponentUtil.translatable("sodium.options.particle_quality.tooltip"))
.setControl(option -> new CyclingControl<>(option, ParticleMode.class, new ITextComponent[] {
ComponentUtil.translatable(ParticleMode.ALL.getTranslationKey()),
ComponentUtil.translatable(ParticleMode.DECREASED.getTranslationKey()),
ComponentUtil.translatable(ParticleMode.MINIMAL.getTranslationKey()) }))
.setBinding((opts, value) -> opts.particleSetting = value.ordinal(), (opts) -> ParticleMode.byId(opts.particleSetting))
.setImpact(OptionImpact.MEDIUM)
.build())
.add(OptionImpl.createBuilder(SmoothLighting.class, vanillaOpts)
.setId(StandardOptions.Option.SMOOTH_LIGHT)
.setName(ComponentUtil.translatable("options.ao"))
.setTooltip(ComponentUtil.translatable("sodium.options.smooth_lighting.tooltip"))
.setControl(option -> new CyclingControl<>(option, SmoothLighting.class, new ITextComponent[] {
ComponentUtil.translatable(SmoothLighting.OFF.getTranslationKey()),
ComponentUtil.translatable(SmoothLighting.MINIMAL.getTranslationKey()),
ComponentUtil.translatable(SmoothLighting.MAXIMUM.getTranslationKey()) }))
.setBinding((opts, value) -> opts.ambientOcclusion = value.getId(), opts -> SmoothLighting.byId(opts.ambientOcclusion))
.setImpact(OptionImpact.LOW)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(boolean.class, vanillaOpts)
.setId(StandardOptions.Option.ENTITY_SHADOWS)
.setName(ComponentUtil.translatable("options.entityShadows"))
.setTooltip(ComponentUtil.translatable("sodium.options.entity_shadows.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.entityShadows = value, opts -> opts.entityShadows)
.setImpact(OptionImpact.LOW)
.build())
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.VIGNETTE)
.setName(ComponentUtil.translatable("sodium.options.vignette.name"))
.setTooltip(ComponentUtil.translatable("sodium.options.vignette.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.quality.enableVignette = value, opts -> opts.quality.enableVignette)
.setImpact(OptionImpact.LOW)
.build())
.build());
groups.add(OptionGroup.createBuilder()
.setId(StandardOptions.Group.MIPMAPS)
.add(OptionImpl.createBuilder(int.class, vanillaOpts)
.setId(StandardOptions.Option.MIPMAP_LEVEL)
.setName(ComponentUtil.translatable("options.mipmapLevels"))
.setTooltip(ComponentUtil.translatable("sodium.options.mipmap_levels.tooltip"))
.setControl(option -> new SliderControl(option, 0, 4, 1, ControlValueFormatter.multiplier()))
.setBinding((opts, value) -> opts.mipmapLevels = value, opts -> opts.mipmapLevels)
.setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_ASSET_RELOAD)
.build())
.build());
groups.add(OptionGroup.createBuilder()
.setId(StandardOptions.Group.SORTING)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.TRANSLUCENT_FACE_SORTING)
.setName(ComponentUtil.translatable("sodium.options.translucent_face_sorting.name"))
.setTooltip(ComponentUtil.translatable("sodium.options.translucent_face_sorting.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.VARIES)
.setBinding((opts, value) -> opts.performance.useTranslucentFaceSorting = value, opts -> opts.performance.useTranslucentFaceSorting)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.build());
return new OptionPage(ComponentUtil.translatable("sodium.options.pages.quality"), ImmutableList.copyOf(groups));
}
public static OptionPage performance() {
List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.setId(StandardOptions.Group.CHUNK_UPDATES)
.add(OptionImpl.createBuilder(int.class, sodiumOpts)
.setId(StandardOptions.Option.CHUNK_UPDATE_THREADS)
.setName(ComponentUtil.translatable("sodium.options.chunk_update_threads.name"))
.setTooltip(ComponentUtil.translatable("sodium.options.chunk_update_threads.tooltip"))
.setControl(o -> new SliderControl(o, 0, ChunkBuilder.getMaxThreadCount(), 1, ControlValueFormatter.quantityOrDisabled("threads", "Default")))
.setImpact(OptionImpact.HIGH)
.setBinding((opts, value) -> opts.performance.chunkBuilderThreads = value, opts -> opts.performance.chunkBuilderThreads)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.DEFFER_CHUNK_UPDATES)
.setName(ComponentUtil.translatable("sodium.options.always_defer_chunk_updates.name"))
.setTooltip(ComponentUtil.translatable("sodium.options.always_defer_chunk_updates.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.HIGH)
.setBinding((opts, value) -> opts.performance.alwaysDeferChunkUpdates = value, opts -> opts.performance.alwaysDeferChunkUpdates)
.setFlags(OptionFlag.REQUIRES_RENDERER_UPDATE)
.build())
.add(OptionImpl.createBuilder(AsyncOcclusionMode.class, sodiumOpts)
.setId(StandardOptions.Option.ASYNC_GRAPH_SEARCH)
.setName(ComponentUtil.translatable("celeritas.options.async_graph_search.name"))
.setTooltip(ComponentUtil.translatable("celeritas.options.async_graph_search.tooltip"))
.setControl(o -> new CyclingControl<>(o, AsyncOcclusionMode.class, new ITextComponent[] {
ComponentUtil.literal("Off"),
ComponentUtil.literal("Only Shadows"),
ComponentUtil.literal("Everything") }))
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.performance.asyncOcclusionMode = value, opts -> opts.performance.asyncOcclusionMode)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.build()
);
groups.add(OptionGroup.createBuilder()
.setId(StandardOptions.Group.RENDERING_CULLING)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.BLOCK_FACE_CULLING)
.setName(ComponentUtil.translatable("sodium.options.use_block_face_culling.name"))
.setTooltip(ComponentUtil.translatable("sodium.options.use_block_face_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.performance.useBlockFaceCulling = value, opts -> opts.performance.useBlockFaceCulling)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.COMPACT_VERTEX_FORMAT)
.setName(ComponentUtil.translatable("sodium.options.use_compact_vertex_format.name"))
.setTooltip(ComponentUtil.translatable("sodium.options.use_compact_vertex_format.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> {
opts.performance.useCompactVertexFormat = value;
}, opts -> opts.performance.useCompactVertexFormat)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.FOG_OCCLUSION)
.setName(ComponentUtil.translatable("sodium.options.use_fog_occlusion.name"))
.setTooltip(ComponentUtil.translatable("sodium.options.use_fog_occlusion.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.performance.useFogOcclusion = value, opts -> opts.performance.useFogOcclusion)
.setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_RENDERER_UPDATE)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.ENTITY_CULLING)
.setName(ComponentUtil.translatable("sodium.options.use_entity_culling.name"))
.setTooltip(ComponentUtil.translatable("sodium.options.use_entity_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.performance.useEntityCulling = value, opts -> opts.performance.useEntityCulling)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.ANIMATE_VISIBLE_TEXTURES)
.setName(ComponentUtil.translatable("sodium.options.animate_only_visible_textures.name"))
.setTooltip(ComponentUtil.translatable("sodium.options.animate_only_visible_textures.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.HIGH)
.setBinding((opts, value) -> opts.performance.animateOnlyVisibleTextures = value, opts -> opts.performance.animateOnlyVisibleTextures)
.setFlags(OptionFlag.REQUIRES_RENDERER_UPDATE)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.RENDER_PASS_CONSOLIDATION)
.setName(ComponentUtil.translatable("celeritas.options.use_render_pass_consolidation.name"))
.setTooltip(ComponentUtil.translatable("celeritas.options.use_render_pass_consolidation.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.LOW)
.setBinding((opts, value) -> opts.performance.useRenderPassConsolidation = value, opts -> opts.performance.useRenderPassConsolidation)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.RENDER_PASS_OPTIMIZATION)
.setName(ComponentUtil.translatable("celeritas.options.use_render_pass_optimization.name"))
.setTooltip(ComponentUtil.translatable("celeritas.options.use_render_pass_optimization.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.LOW)
.setBinding((opts, value) -> opts.performance.useRenderPassOptimization = value, opts -> opts.performance.useRenderPassOptimization)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.build());
return new OptionPage(ComponentUtil.translatable("sodium.options.pages.performance"), ImmutableList.copyOf(groups));
}
public static OptionPage advanced() {
List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.setId(StandardOptions.Group.CPU_SAVING)
.add(OptionImpl.createBuilder(int.class, sodiumOpts)
.setId(StandardOptions.Option.CPU_FRAMES_AHEAD)
.setName(ComponentUtil.translatable("sodium.options.cpu_render_ahead_limit.name"))
.setTooltip(ComponentUtil.translatable("sodium.options.cpu_render_ahead_limit.tooltip"))
.setControl(opt -> new SliderControl(opt, 0, 9, 1, ControlValueFormatter.translateVariable("sodium.options.cpu_render_ahead_limit.value")))
.setBinding((opts, value) -> opts.advanced.cpuRenderAheadLimit = value, opts -> opts.advanced.cpuRenderAheadLimit)
.build()
)
.build());
return new OptionPage(ComponentUtil.translatable("sodium.options.pages.advanced"), ImmutableList.copyOf(groups));
}
public static OptionStorage<GameSettings> getVanillaOpts() {
return vanillaOpts;
}
public static OptionStorage<SodiumGameOptions> getSodiumOpts() {
return sodiumOpts;
}
}
@@ -0,0 +1,182 @@
package org.taumc.celeritas.impl.gui;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.annotations.SerializedName;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import net.minecraft.client.Minecraft;
import net.minecraft.util.text.ITextComponent;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode;
import org.taumc.celeritas.CeleritasVintage;
import org.taumc.celeritas.impl.config.ConfigMigrator;
import org.taumc.celeritas.impl.gui.options.TextProvider;
import org.taumc.celeritas.impl.util.ComponentUtil;
public class SodiumGameOptions {
private static final String DEFAULT_FILE_NAME = "celeritas-options.json";
public final QualitySettings quality = new QualitySettings();
public final AdvancedSettings advanced = new AdvancedSettings();
public final PerformanceSettings performance = new PerformanceSettings();
public final NotificationSettings notifications = new NotificationSettings();
private boolean readOnly;
private Path configPath;
private static final Gson GSON;
public static SodiumGameOptions defaults() {
SodiumGameOptions options = new SodiumGameOptions();
options.configPath = getConfigPath("celeritas-options.json");
return options;
}
public static SodiumGameOptions load() {
return load("celeritas-options.json");
}
public static SodiumGameOptions load(String name) {
Path path = getConfigPath(name);
boolean resaveConfig = true;
SodiumGameOptions config;
if (Files.exists(path)) {
try (FileReader reader = new FileReader(path.toFile())) {
config = GSON.fromJson(reader, SodiumGameOptions.class);
} catch (IOException e) {
throw new RuntimeException("Could not parse config", e);
} catch (JsonSyntaxException e) {
CeleritasVintage.logger().error("Could not parse config, will fallback to default settings", e);
config = new SodiumGameOptions();
resaveConfig = false;
}
} else {
config = new SodiumGameOptions();
}
config.configPath = path;
config.notifications.forceDisableDonationPrompts = false;
try {
if (resaveConfig) {
config.writeChanges();
}
return config;
} catch (IOException e) {
throw new RuntimeException("Couldn't update config file", e);
}
}
private static Path getConfigPath(String name) {
return ConfigMigrator.handleConfigMigration(name);
}
/** @deprecated */
@Deprecated
public void writeChanges() throws IOException {
writeToDisk(this);
}
public static void writeToDisk(SodiumGameOptions config) throws IOException {
if (config.isReadOnly()) {
throw new IllegalStateException("Config file is read-only");
} else {
Path dir = config.configPath.getParent();
if (!Files.exists(dir)) {
Files.createDirectories(dir);
} else if (!Files.isDirectory(dir)) {
throw new IOException("Not a directory: " + dir);
}
Path tempPath = config.configPath.resolveSibling(config.configPath.getFileName() + ".tmp");
Files.writeString(tempPath, GSON.toJson(config));
Files.move(tempPath, config.configPath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
}
}
public boolean isReadOnly() {
return this.readOnly;
}
public void setReadOnly() {
this.readOnly = true;
}
public String getFileName() {
return this.configPath.getFileName().toString();
}
static {
GSON = (new GsonBuilder()).setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setPrettyPrinting().excludeFieldsWithModifiers(new int[]{2}).create();
}
public static class PerformanceSettings {
public int chunkBuilderThreads = 0;
@SerializedName("always_defer_chunk_updates_v2")
public boolean alwaysDeferChunkUpdates = true;
public boolean animateOnlyVisibleTextures = true;
public boolean useEntityCulling = true;
public boolean useFogOcclusion = true;
public boolean useBlockFaceCulling = true;
public boolean useCompactVertexFormat = false;
@SerializedName("use_translucent_face_sorting_v2")
public boolean useTranslucentFaceSorting = true;
public boolean useRenderPassOptimization = true;
public boolean useRenderPassConsolidation = true;
public AsyncOcclusionMode asyncOcclusionMode;
public PerformanceSettings() {
this.asyncOcclusionMode = AsyncOcclusionMode.ONLY_SHADOW;
}
}
public static class AdvancedSettings {
public int cpuRenderAheadLimit = 3;
}
public static class QualitySettings {
public GraphicsQuality weatherQuality;
public GraphicsQuality leavesQuality;
public boolean enableVignette;
public QualitySettings() {
this.weatherQuality = SodiumGameOptions.GraphicsQuality.DEFAULT;
this.leavesQuality = SodiumGameOptions.GraphicsQuality.DEFAULT;
this.enableVignette = true;
}
}
public static class NotificationSettings {
public boolean forceDisableDonationPrompts = false;
public boolean hasClearedDonationButton = false;
public boolean hasSeenDonationPrompt = false;
}
public enum GraphicsQuality implements TextProvider {
DEFAULT("generator.default"),
FANCY("options.clouds.fancy"),
FAST("options.clouds.fast");
private final ITextComponent name;
GraphicsQuality(String name) {
this.name = ComponentUtil.translatable(name);
}
public ITextComponent getLocalizedName() {
return this.name;
}
public boolean isFancy(boolean fancyGraphics) {
return this == FANCY || this == DEFAULT && fancyGraphics;
}
public boolean isFancy() {
return this.isFancy(Minecraft.getMinecraft().gameSettings.fancyGraphics);
}
}
}
@@ -0,0 +1,52 @@
package org.taumc.celeritas.impl.gui.compat;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
public interface Element {
default boolean mouseClicked(double mouseX, double mouseY, int button) {
return false;
}
default boolean mouseReleased(double mouseX, double mouseY, int button) {
return false;
}
default boolean mouseDragged(double mouseX, double mouseY, int button, double dragX, double dragY) {
return false;
}
default boolean mouseScrolled(double mouseX, double mouseY, double delta) {
return false;
}
default boolean keyPressed(int keyCode) {
return false;
}
default boolean charTyped(char codePoint) {
return false;
}
default boolean isMouseOver(double d, double e) {
return false;
}
default boolean isDragging() {
return false;
}
default void setDragging(boolean dragging) {
}
void setFocused(boolean focused);
boolean isFocused();
default List<? extends Element> children() {
return Collections.emptyList();
}
}
@@ -0,0 +1,46 @@
package org.taumc.celeritas.impl.gui.compat;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import org.lwjgl.opengl.GL20C;
public class GuiGraphics {
public int drawString(FontRenderer font, String str, int x, int y, int color) {
return this.drawString(font, str, x, y, color, true);
}
public void drawString(FontRenderer font, ITextComponent component, int x, int y, int color) {
this.drawString(font, component.getFormattedText(), x, y, color, true);
}
public int drawString(FontRenderer font, String str, int x, int y, int color, boolean shadow) {
return shadow ? font.drawStringWithShadow(str, (float)x, (float)y, color) : font.drawString(str, x, y, color);
}
public void fill(int x1, int y1, int x2, int y2, int color) {
Gui.drawRect(x1, y1, x2, y2, color);
}
public void enableScissor(int x, int y, int x2, int y2) {
int width = x2 - x + 1;
int height = y2 - y + 1;
var mc = Minecraft.getMinecraft();
ScaledResolution scaledresolution = new ScaledResolution(mc);
int scale = scaledresolution.getScaleFactor();
GL20C.glEnable(3089);
GL20C.glScissor(x * scale, mc.displayHeight - (y + height) * scale, width * scale, height * scale);
}
public void disableScissor() {
GL20C.glDisable(3089);
}
public void blit(ResourceLocation icon, int x, int y, float u, float v, int width, int height, int textureWidth, int textureHeight) {
Minecraft.getMinecraft().getTextureManager().bindTexture(icon);
Gui.drawModalRectWithCustomSizedTexture(x, y, u, v, width, height, (float)textureWidth, (float)textureHeight);
}
}
@@ -0,0 +1,5 @@
package org.taumc.celeritas.impl.gui.compat;
public interface Renderable {
void render(GuiGraphics var1, int var2, int var3, float var4);
}
@@ -0,0 +1,110 @@
package org.taumc.celeritas.impl.gui.frame;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL20C;
import org.taumc.celeritas.api.options.control.ControlElement;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.gui.compat.Renderable;
import org.taumc.celeritas.impl.gui.widgets.AbstractWidget;
import org.taumc.celeritas.impl.util.Dim2i;
import org.taumc.celeritas.impl.gui.compat.Element;
public abstract class AbstractFrame extends AbstractWidget implements Element {
protected Dim2i dim;
protected final List<AbstractWidget> children = new ArrayList<>();
protected final List<Renderable> drawable = new ArrayList<>();
protected final List<ControlElement<?>> controlElements = new ArrayList<>();
protected boolean renderOutline;
private Element focused;
private boolean dragging;
private Consumer<Element> focusListener;
public AbstractFrame(Dim2i dim, boolean renderOutline) {
this.dim = dim;
this.renderOutline = renderOutline;
}
public void buildFrame() {
for (Element element : this.children) {
if (element instanceof AbstractFrame) {
this.controlElements.addAll(((AbstractFrame) element).controlElements);
}
if (element instanceof ControlElement<?>) {
this.controlElements.add((ControlElement<?>) element);
}
if (element instanceof Renderable) {
this.drawable.add((Renderable) element);
}
}
}
@Override
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) {
if (this.renderOutline) {
this.drawBorder(drawContext, this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), -5592406);
}
for (Renderable drawable : this.drawable) {
drawable.render(drawContext, mouseX, mouseY, delta);
}
}
public void applyScissor(int x, int y, int width, int height, Runnable action) {
ScaledResolution scaled = new ScaledResolution(Minecraft.getMinecraft());
double scale = (double) Minecraft.getMinecraft().displayWidth / (double) scaled.getScaledWidth();
GL20C.glEnable(3089);
GL20C.glScissor((int) ((double) x * scale), (int) ((double) Minecraft.getMinecraft().displayHeight - (double) (y + height) * scale), (int) ((double) width * scale), (int) ((double) height * scale));
action.run();
GL20C.glDisable(3089);
}
public void registerFocusListener(Consumer<Element> focusListener) {
this.focusListener = focusListener;
}
@Override
public boolean isDragging() {
return this.dragging;
}
@Override
public void setDragging(boolean dragging) {
this.dragging = dragging;
}
@Nullable
public Element getFocused() {
return this.focused;
}
public void setFocused(@Nullable Element focused) {
this.focused = focused;
if (this.focusListener != null) {
this.focusListener.accept(focused);
}
}
@Override
public List<? extends Element> children() {
return this.children;
}
@Override
public boolean isMouseOver(double mouseX, double mouseY) {
return this.dim.containsCursor(mouseX, mouseY);
}
public Dim2i getDimensions() {
return this.dim;
}
}
@@ -0,0 +1,57 @@
package org.taumc.celeritas.impl.gui.frame;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import org.apache.commons.lang3.Validate;
import org.taumc.celeritas.impl.gui.widgets.AbstractWidget;
import org.taumc.celeritas.impl.util.Dim2i;
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(this.dim)));
super.buildFrame();
}
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,220 @@
package org.taumc.celeritas.impl.gui.frame;
import com.google.common.collect.UnmodifiableIterator;
import java.util.ArrayList;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Stream;
import net.minecraft.client.Minecraft;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextFormatting;
import org.apache.commons.lang3.Validate;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL11;
import org.taumc.celeritas.api.options.OptionIdentifier;
import org.taumc.celeritas.api.options.control.Control;
import org.taumc.celeritas.api.options.control.ControlElement;
import org.taumc.celeritas.api.options.structure.Option;
import org.taumc.celeritas.api.options.structure.OptionGroup;
import org.taumc.celeritas.api.options.structure.OptionImpact;
import org.taumc.celeritas.api.options.structure.OptionPage;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.gui.theme.DefaultColors;
import org.taumc.celeritas.impl.util.ComponentUtil;
import org.taumc.celeritas.impl.util.Dim2i;
import org.taumc.celeritas.impl.util.PlatformUtil;
public class OptionPageFrame extends AbstractFrame {
protected final OptionPage page;
private long lastTime = 0L;
private ControlElement<?> lastHoveredElement = null;
protected final Predicate<Option<?>> optionFilter;
public OptionPageFrame(Dim2i dim, boolean renderOutline, OptionPage page, Predicate<Option<?>> optionFilter) {
super(dim, renderOutline);
this.page = page;
this.optionFilter = optionFilter;
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()) {
int visibleOptionCount = (int) group.getOptions().stream().filter(optionFilter::test).count();
y += visibleOptionCount * 18;
if (visibleOptionCount > 0 && group != lastGroup) {
y += 4;
}
}
}
this.dim = this.dim.withHeight(y);
}
@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()) {
boolean needPadding = false;
// Add each option's control element
for (Option<?> option : group.getOptions()) {
if (!optionFilter.test(option)) {
continue;
}
Control<?> control = option.getControl();
Dim2i dim = new Dim2i(0, y, this.dim.width(), 18).withParentOffset(this.dim);
ControlElement<?> element = control.createElement(dim);
this.children.add(element);
// Move down to the next option
y += 18;
needPadding = true;
}
if (needPadding) {
// Add padding beneath each option group
y += 4;
}
}
super.buildFrame();
}
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) {
ControlElement<?> hoveredElement = this.controlElements.stream()
.filter(ControlElement::isHovered)
.findFirst()
.orElse(this.controlElements.stream()
.filter(ControlElement::isFocused)
.findFirst()
.orElse(null));
super.render(drawContext, mouseX, mouseY, delta);
if (hoveredElement != null && this.lastHoveredElement == hoveredElement &&
((this.dim.containsCursor(mouseX, mouseY) && hoveredElement.isHovered() && hoveredElement.isMouseOver(mouseX, mouseY))
|| hoveredElement.isFocused())) {
if (this.lastTime == 0) {
this.lastTime = System.currentTimeMillis();
}
this.renderOptionTooltip(drawContext, hoveredElement);
} else {
this.lastTime = 0;
this.lastHoveredElement = hoveredElement;
}
}
private static String normalizeModForTooltip(@Nullable String mod) {
if (mod == null) {
return null;
} else {
return switch (mod) {
case "minecraft" -> "celeritas";
default -> mod;
};
}
}
private void renderOptionTooltip(GuiGraphics drawContext, ControlElement<?> element) {
if (this.lastTime + 500 > System.currentTimeMillis()) return;
Dim2i dim = element.getDimensions();
int textPadding = 3;
int boxPadding = 3;
int boxWidth = dim.width();
int boxY = dim.getLimitY();
int boxX = dim.x();
Option<?> option = element.getOption();
ArrayList<String> tooltip = new ArrayList<>(split(option.getTooltip().getFormattedText(), boxWidth - textPadding * 2));
OptionImpact impact = option.getImpact();
if (impact != null) {
ITextComponent impactString = ComponentUtil.translatable("sodium.options.performance_impact_string", impact.getLocalizedName()).setStyle((new Style()).setColor(TextFormatting.GRAY));
tooltip.add(impactString.getFormattedText());
}
OptionIdentifier<?> id = option.getId();
if (OptionIdentifier.isPresent(this.page.getId()) && OptionIdentifier.isPresent(id) && !Objects.equals(normalizeModForTooltip(this.page.getId().getModId()), normalizeModForTooltip(id.getModId()))) {
ITextComponent addedByModString = ComponentUtil.translatable("celeritas.options.added_by_mod_string", ComponentUtil.literal(PlatformUtil.getModName(id.getModId())).setStyle((new Style()).setColor(TextFormatting.WHITE).setColor(TextFormatting.GRAY)));
tooltip.add(addedByModString.getFormattedText());
}
int boxHeight = tooltip.size() * 12 + boxPadding;
int boxYLimit = boxY + boxHeight;
int boxYCutoff = this.dim.getLimitY();
if (boxYLimit > boxYCutoff) {
boxY -= boxHeight + dim.height();
}
if (boxY < 0) {
boxY = dim.getLimitY();
}
GL11.glPushMatrix();
GL11.glTranslated(0.0F, 0.0F, 90.0F);
this.drawRect(drawContext, boxX, boxY, boxX + boxWidth, boxY + boxHeight, 0xE0000000);
this.drawBorder(drawContext, boxX, boxY, boxX + boxWidth, boxY + boxHeight, DefaultColors.ELEMENT_ACTIVATED);
for (int i = 0; i < tooltip.size(); ++i) {
drawContext.drawString(Minecraft.getMinecraft().fontRenderer, tooltip.get(i), boxX + textPadding, boxY + textPadding + i * 12, -1, true);
}
GL11.glPopMatrix();
}
public static class Builder {
private Dim2i dim;
private boolean renderOutline;
private OptionPage page;
private Predicate<Option<?>> optionFilter = o -> true;
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 Builder setOptionFilter(Predicate<Option<?>> optionFilter) {
this.optionFilter = optionFilter;
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, this.optionFilter);
}
}
}
@@ -0,0 +1,205 @@
package org.taumc.celeritas.impl.gui.frame;
import java.util.concurrent.atomic.AtomicReference;
import org.lwjgl.opengl.GL11;
import org.taumc.celeritas.api.options.control.ControlElement;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.gui.frame.components.ScrollBarComponent;
import org.taumc.celeritas.impl.util.Dim2i;
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.x(), frame.dim.y(), 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.x() - this.dim.x() + this.frame.dim.width();
if (maxWidth < value) {
maxWidth = value;
}
}
if (this.dim.getLimitY() < this.frame.dim.getLimitY()) {
int value = this.frame.dim.y() - this.dim.y() + this.frame.dim.height();
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.x(), this.dim.y(), this.dim.width() - 11, this.dim.height() - 11);
} else if (this.canScrollHorizontal) {
this.viewPortDimension = new Dim2i(this.dim.x(), this.dim.y(), this.dim.width(), this.dim.height() - 11);
this.frame.dim = this.frame.dim.withHeight(this.frame.dim.height() - 11); // FIXME don't mutate
} else if (this.canScrollVertical) {
this.viewPortDimension = new Dim2i(this.dim.x(), this.dim.y(), this.dim.width() - 11, this.dim.height());
this.frame.dim = this.frame.dim.withWidth(this.frame.dim.width() - 11); // FIXME don't mutate
}
if (this.canScrollHorizontal) {
this.horizontalScrollBar = new ScrollBarComponent(new Dim2i(this.viewPortDimension.x(), this.viewPortDimension.getLimitY() + 1, this.viewPortDimension.width(), 10), ScrollBarComponent.Mode.HORIZONTAL, this.frame.dim.width(), this.viewPortDimension.width(), horizontalScrollBarOffset::set);
this.horizontalScrollBar.setOffset(horizontalScrollBarOffset.get());
}
if (this.canScrollVertical) {
this.verticalScrollBar = new ScrollBarComponent(new Dim2i(this.viewPortDimension.getLimitX() + 1, this.viewPortDimension.y(), 10, this.viewPortDimension.height()), ScrollBarComponent.Mode.VERTICAL, this.frame.dim.height(), this.viewPortDimension.height(), verticalScrollBarOffset::set, 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();
}
this.frame.buildFrame();
this.children.add(this.frame);
super.buildFrame();
// fixme: Ridiculous hack to snap to focused element
// for the meanwhile this works until a proper solution is implemented.
// this shouldn't be hardcoded into scrollable frame
this.frame.registerFocusListener(element -> {
if (element instanceof ControlElement<?> controlElement && this.canScrollVertical) {
Dim2i dim = controlElement.getDimensions();
int inputOffset = this.verticalScrollBar.getOffset();
int elementTop = dim.y() - inputOffset;
int elementBottom = dim.getLimitY() - inputOffset;
if (elementTop <= this.viewPortDimension.y()) {
inputOffset += elementTop - this.viewPortDimension.y();
} else if (elementBottom >= this.viewPortDimension.getLimitY()) {
inputOffset += elementBottom - this.viewPortDimension.getLimitY();
}
this.verticalScrollBar.setOffset(inputOffset);
}
});
}
private double applyOffset(ScrollBarComponent component, double coord, boolean negate) {
if(component == null) {
return coord;
} else {
return coord + (component.getOffset() * (negate ? -1 : 1));
}
}
@Override
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) {
if (!this.canScrollHorizontal && !this.canScrollVertical) {
super.render(drawContext, mouseX, mouseY, delta);
} else {
if (this.renderOutline) {
this.drawBorder(drawContext, this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), -5592406);
}
boolean mouseInViewport = this.viewPortDimension.containsCursor(mouseX, mouseY);
drawContext.enableScissor(this.viewPortDimension.x(), this.viewPortDimension.y(), this.viewPortDimension.getLimitX(), this.viewPortDimension.getLimitY());
GL11.glPushMatrix();
GL11.glTranslatef((float)this.applyOffset(this.horizontalScrollBar, 0.0F, true), (float)this.applyOffset(this.verticalScrollBar, 0.0F, true), 0.0F);
super.render(drawContext, mouseInViewport ? (int)this.applyOffset(this.horizontalScrollBar, mouseX, false) : -1, mouseInViewport ? (int)this.applyOffset(this.verticalScrollBar, mouseY, false) : -1, delta);
GL11.glPopMatrix();
drawContext.disableScissor();
}
if (this.canScrollHorizontal) {
this.horizontalScrollBar.render(drawContext, mouseX, mouseY, delta);
}
if (this.canScrollVertical) {
this.verticalScrollBar.render(drawContext, mouseX, mouseY, delta);
}
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
return this.canScrollHorizontal && this.horizontalScrollBar.mouseClicked(mouseX, mouseY, button) || this.canScrollVertical && this.verticalScrollBar.mouseClicked(mouseX, mouseY, button) || super.mouseClicked(this.applyOffset(this.horizontalScrollBar, mouseX, false), this.applyOffset(this.verticalScrollBar, mouseY, false), button);
}
@Override
public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) {
return this.canScrollHorizontal && this.horizontalScrollBar.mouseDragged(mouseX, mouseY, button, deltaX, deltaY) || this.canScrollVertical && this.verticalScrollBar.mouseDragged(mouseX, mouseY, button, deltaX, deltaY) || super.mouseDragged(this.applyOffset(this.horizontalScrollBar, mouseX, false), this.applyOffset(this.verticalScrollBar, mouseY, false), button, deltaX, deltaY);
}
@Override
public boolean mouseReleased(double mouseX, double mouseY, int button) {
return this.canScrollHorizontal && this.horizontalScrollBar.mouseReleased(mouseX, mouseY, button) || this.canScrollVertical && this.verticalScrollBar.mouseReleased(mouseX, mouseY, button) || super.mouseReleased(this.applyOffset(this.horizontalScrollBar, mouseX, false), this.applyOffset(this.verticalScrollBar, mouseY, false), button);
}
@Override
public boolean mouseScrolled(double mouseX, double mouseY, double verticalAmount) {
return this.canScrollHorizontal && this.horizontalScrollBar.mouseScrolled(mouseX, mouseY, verticalAmount) || this.canScrollVertical && this.verticalScrollBar.mouseScrolled(mouseX, mouseY, verticalAmount) || super.mouseScrolled(this.applyOffset(this.horizontalScrollBar, mouseX, false), this.applyOffset(this.verticalScrollBar, mouseY, false), verticalAmount);
}
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,169 @@
package org.taumc.celeritas.impl.gui.frame.components;
import java.util.function.Consumer;
import org.jetbrains.annotations.Nullable;
import org.taumc.celeritas.impl.gui.compat.Element;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.gui.widgets.AbstractWidget;
import org.taumc.celeritas.impl.util.Dim2i;
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;
private int offset;
private boolean isDragging;
private Dim2i scrollThumb;
private int scrollThumbClickOffset;
private Dim2i extendedScrollArea;
public ScrollBarComponent(Dim2i trackArea, Mode mode, int frameLength, int viewPortLength, Consumer<Integer> onSetOffset) {
this.offset = 0;
this.scrollThumb = null;
this.extendedScrollArea = null;
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 == ScrollBarComponent.Mode.VERTICAL ? this.dim.height() : this.dim.width() - 6) / this.frameLength;
int maximumScrollThumbOffset = this.viewPortLength - scrollThumbLength;
int scrollThumbOffset = this.offset * maximumScrollThumbOffset / this.maxScrollBarOffset;
this.scrollThumb = new Dim2i(this.dim.x() + 2 + (this.mode == ScrollBarComponent.Mode.HORIZONTAL ? scrollThumbOffset : 0), this.dim.y() + 2 + (this.mode == ScrollBarComponent.Mode.VERTICAL ? scrollThumbOffset : 0), (this.mode == ScrollBarComponent.Mode.VERTICAL ? this.dim.width() : scrollThumbLength) - 4, (this.mode == ScrollBarComponent.Mode.VERTICAL ? scrollThumbLength : this.dim.height()) - 4);
}
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) {
this.drawBorder(drawContext, this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), -5592406);
this.drawRect(drawContext, this.scrollThumb.x(), this.scrollThumb.y(), this.scrollThumb.getLimitX(), this.scrollThumb.getLimitY(), -5592406);
if (this.isFocused()) {
this.drawBorder(drawContext, this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), -1);
}
}
@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 == ScrollBarComponent.Mode.VERTICAL) {
this.scrollThumbClickOffset = (int)(mouseY - ((double)this.scrollThumb.y() + (double)this.scrollThumb.height() / (double)2.0F));
} else {
this.scrollThumbClickOffset = (int)(mouseX - ((double)this.scrollThumb.x() + (double)this.scrollThumb.width() / (double)2.0F));
}
this.isDragging = true;
} else {
int value;
if (this.mode == ScrollBarComponent.Mode.VERTICAL) {
value = (int)((mouseY - (double)this.dim.y() - (double)this.scrollThumb.height() / (double)2.0F) / (double)(this.dim.height() - this.scrollThumb.height()) * (double)this.maxScrollBarOffset);
} else {
value = (int)((mouseX - (double)this.dim.x() - (double)this.scrollThumb.width() / (double)2.0F) / (double)(this.dim.width() - this.scrollThumb.width()) * (double)this.maxScrollBarOffset);
}
this.setOffset(value);
this.isDragging = false;
}
return true;
} else {
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, double deltaX, double deltaY) {
if (this.isDragging) {
int value;
if (this.mode == ScrollBarComponent.Mode.VERTICAL) {
value = (int)((mouseY - (double)this.scrollThumbClickOffset - (double)this.dim.y() - (double)this.scrollThumb.height() / (double)2.0F) / (double)(this.dim.height() - this.scrollThumb.height()) * (double)this.maxScrollBarOffset);
} else {
value = (int)((mouseX - (double)this.scrollThumbClickOffset - (double)this.dim.x() - (double)this.scrollThumb.width() / (double)2.0F) / (double)(this.dim.width() - this.scrollThumb.width()) * (double)this.maxScrollBarOffset);
}
this.setOffset(value);
return true;
} else {
return false;
}
}
public boolean mouseScrolled(double mouseX, double mouseY, double verticalAmount) {
if ((this.dim.containsCursor(mouseX, mouseY) || this.extendedScrollArea != null && this.extendedScrollArea.containsCursor(mouseX, mouseY)) && this.offset <= this.maxScrollBarOffset && this.offset >= 0) {
int value = (int)((double)this.offset - verticalAmount * (double)6.0F);
this.setOffset(value);
return true;
} else {
return false;
}
}
public int getOffset() {
return this.offset;
}
public void setOffset(int value) {
this.offset = Math.clamp(value, 0, this.maxScrollBarOffset);
this.updateThumbPosition();
this.onSetOffset.accept(this.offset);
}
@Override
public boolean keyPressed(int keyCode) {
if (!this.isFocused()) {
return false;
} else {
if (this.mode == ScrollBarComponent.Mode.VERTICAL) {
if (keyCode == 200) {
this.setOffset(this.getOffset() - 6);
return true;
}
if (keyCode == 208) {
this.setOffset(this.getOffset() + 6);
return true;
}
} else {
if (keyCode == 203) {
this.setOffset(this.getOffset() - 6);
return true;
}
if (keyCode == 205) {
this.setOffset(this.getOffset() + 6);
return true;
}
}
return false;
}
}
public enum Mode {
HORIZONTAL,
VERTICAL
}
}
@@ -0,0 +1,231 @@
package org.taumc.celeritas.impl.gui.frame.components;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.util.ChatAllowedCharacters;
import org.taumc.celeritas.api.options.structure.OptionPage;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.gui.widgets.AbstractWidget;
import org.taumc.celeritas.impl.util.ComponentUtil;
import org.taumc.celeritas.impl.util.Dim2i;
public class SearchTextFieldComponent extends AbstractWidget {
protected final Dim2i dim;
protected final List<OptionPage> pages;
private final FontRenderer textRenderer;
private final SearchTextFieldModel model;
public SearchTextFieldComponent(Dim2i dim, List<OptionPage> pages, SearchTextFieldModel model) {
this.textRenderer = Minecraft.getMinecraft().fontRenderer;
this.dim = dim;
this.pages = pages;
this.model = model;
}
@Override
public void render(GuiGraphics context, int mouseX, int mouseY, float delta) {
this.model.innerWidth = this.getInnerWidth();
if (this.isVisible()) {
if (this.model.text.isEmpty()) {
this.drawString(context, ComponentUtil.translatable("celeritas.search_bar_empty"), this.dim.x() + 6, this.dim.y() + 6, -5592406);
}
this.drawRect(context, this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), this.isFocused() ? -536870912 : -1879048192);
int j = this.model.selectionStart - this.model.firstCharacterIndex;
int k = this.model.selectionEnd - this.model.firstCharacterIndex;
String string = this.textRenderer.trimStringToWidth(this.model.text.substring(this.model.firstCharacterIndex), this.getInnerWidth());
boolean bl = j >= 0 && j <= string.length();
int l = this.dim.x() + 6;
int m = this.dim.y() + 6;
int n = l;
if (k > string.length()) {
k = string.length();
}
if (!string.isEmpty()) {
String string2 = bl ? string.substring(0, j) : string;
n = context.drawString(this.textRenderer, string2, l, m, -1);
}
boolean bl3 = this.model.selectionStart < this.model.text.length() || this.model.text.length() >= this.model.getMaxLength();
int o = n;
if (!bl) {
o = j > 0 ? l + this.dim.width() - 12 : l;
} else if (bl3) {
o = n - 1;
--n;
}
if (!string.isEmpty() && bl && j < string.length()) {
context.drawString(this.textRenderer, string.substring(j), n, m, -1);
}
if (this.isFocused()) {
context.fill(o, m - 1, o + 1, m + 1 + this.textRenderer.FONT_HEIGHT, -3092272);
}
if (k != j) {
int p = l + this.textRenderer.getStringWidth(string.substring(0, k));
this.drawSelectionHighlight(context, o, m - 1, p - 1, m + 1 + this.textRenderer.FONT_HEIGHT);
}
}
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
int i = (int)(Math.floor(mouseX) - (double)this.dim.x() - (double)6.0F);
String string = this.textRenderer.trimStringToWidth(this.model.text.substring(this.model.firstCharacterIndex), this.getInnerWidth());
this.model.setCursor(this.textRenderer.trimStringToWidth(string, i).length() + this.model.firstCharacterIndex);
this.setFocused(this.dim.containsCursor(mouseX, mouseY));
return this.isFocused();
}
@Override
public void setFocused(boolean focused) {
this.focused = focused;
}
private void drawSelectionHighlight(GuiGraphics context, int x1, int y1, int x2, int y2) {
if (x1 < x2) {
int i = x1;
x1 = x2;
x2 = i;
}
if (y1 < y2) {
int i = y1;
y1 = y2;
y2 = i;
}
if (x2 > this.dim.x() + this.dim.width()) {
x2 = this.dim.x() + this.dim.width();
}
if (x1 > this.dim.x() + this.dim.width()) {
x1 = this.dim.x() + this.dim.width();
}
context.fill(x1, y1, x2, y2, -16776961);
}
public boolean isActive() {
return this.isVisible() && this.isFocused() && this.isEditable();
}
@Override
public boolean charTyped(char chr) {
if (!this.isActive()) {
return false;
} else if (ChatAllowedCharacters.isAllowedCharacter(chr)) {
if (this.model.editable) {
this.model.write(Character.toString(chr));
}
return true;
} else {
return false;
}
}
@Override
public boolean keyPressed(int keyCode) {
if (!this.isActive()) {
return false;
} else {
this.model.selecting = GuiScreen.isShiftKeyDown();
if (GuiScreen.isKeyComboCtrlA(keyCode)) {
this.model.setCursorToEnd();
this.model.setSelectionEnd(0);
return true;
} else if (GuiScreen.isKeyComboCtrlC(keyCode)) {
GuiScreen.setClipboardString(this.model.getSelectedText());
return true;
} else if (GuiScreen.isKeyComboCtrlV(keyCode)) {
if (this.model.editable) {
this.model.write(GuiScreen.getClipboardString());
}
return true;
} else if (GuiScreen.isKeyComboCtrlX(keyCode)) {
GuiScreen.setClipboardString(this.model.getSelectedText());
if (this.model.editable) {
this.model.write("");
}
return true;
} else {
switch (keyCode) {
case 14 -> { // Backspace
if (this.model.editable) {
this.model.selecting = false;
this.model.erase(-1);
this.model.selecting = GuiScreen.isShiftKeyDown();
}
return true;
}
case 211 -> { // Delete
if (this.model.editable) {
this.model.selecting = false;
this.model.erase(1);
this.model.selecting = GuiScreen.isShiftKeyDown();
}
return true;
}
case 205 -> { // Right arrow
if (GuiScreen.isCtrlKeyDown()) {
this.model.setCursor(this.model.getWordSkipPosition(1));
} else {
this.model.moveCursor(1);
}
boolean state = this.model.getCursor() != this.model.lastCursorPosition && this.model.getCursor() != this.model.text.length() + 1;
this.model.lastCursorPosition = this.model.getCursor();
return state;
}
case 203 -> { // Left arrow
if (GuiScreen.isCtrlKeyDown()) {
this.model.setCursor(this.model.getWordSkipPosition(-1));
} else {
this.model.moveCursor(-1);
}
boolean state = this.model.getCursor() != this.model.lastCursorPosition && this.model.getCursor() != 0;
this.model.lastCursorPosition = this.model.getCursor();
return state;
}
case 199 -> { // Home
this.model.setCursorToStart();
return true;
}
case 207 -> { // End
this.model.setCursorToEnd();
return true;
}
default -> {
return false;
}
}
}
}
}
public boolean isVisible() {
return this.model.visible;
}
public boolean isEditable() {
return this.model.editable;
}
public int getInnerWidth() {
return this.dim.width() - 12;
}
@Override
public boolean isMouseOver(double mouseX, double mouseY) {
return this.dim.containsCursor(mouseX, mouseY);
}
}
@@ -0,0 +1,249 @@
package org.taumc.celeritas.impl.gui.frame.components;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.util.ChatAllowedCharacters;
import net.minecraft.util.text.ITextComponent;
import org.lwjgl.input.Keyboard;
import org.taumc.celeritas.api.options.control.Control;
import org.taumc.celeritas.api.options.control.CyclingControl;
import org.taumc.celeritas.api.options.structure.Option;
import org.taumc.celeritas.api.options.structure.OptionPage;
import org.taumc.celeritas.impl.gui.CeleritasVideoOptionsScreen;
import org.taumc.celeritas.impl.util.StringUtils;
public class SearchTextFieldModel {
boolean selecting;
String text = "";
int maxLength = 100;
boolean visible = true;
boolean editable = true;
int firstCharacterIndex;
int selectionStart;
int selectionEnd;
int lastCursorPosition = this.getCursor();
Set<Option<?>> selectedOptions;
final Set<Option<?>> allOptions;
final Collection<OptionPage> pages;
int innerWidth;
CeleritasVideoOptionsScreen mainScreen;
public SearchTextFieldModel(Collection<OptionPage> pages, CeleritasVideoOptionsScreen mainScreen) {
this.pages = pages;
this.allOptions = pages.stream().flatMap((p) -> p.getOptions().stream()).collect(Collectors.toUnmodifiableSet());
this.selectedOptions = this.allOptions;
this.mainScreen = mainScreen;
}
int getMaxLength() {
return this.maxLength;
}
public String getSelectedText() {
int i = Math.min(this.selectionStart, this.selectionEnd);
int j = Math.max(this.selectionStart, this.selectionEnd);
return this.text.substring(i, j);
}
public void write(String text) {
int i = Math.min(this.selectionStart, this.selectionEnd);
int j = Math.max(this.selectionStart, this.selectionEnd);
int k = this.maxLength - this.text.length() - (i - j);
String string = filterText(text);
int l = string.length();
if (k < l) {
string = string.substring(0, k);
l = k;
}
String string2 = (new StringBuilder(this.text)).replace(i, j, string).toString();
if (string2 != null) {
this.text = string2;
this.setSelectionStart(i + l);
this.setSelectionEnd(this.selectionStart);
this.onChanged(this.text);
}
}
public Predicate<Option<?>> getOptionPredicate() {
return selectedOptions == allOptions ? (o -> true) : selectedOptions::contains;
}
private void onChanged(String newText) {
this.selectedOptions = this.allOptions;
if (this.editable && !newText.trim().isEmpty()) {
List<Option<?>> fuzzy = StringUtils.fuzzySearch(() -> this.pages.stream().flatMap((p) -> p.getOptions().stream()).iterator(), newText, 2, (o) -> {
String name = o.getName().getFormattedText();
Control patt0$temp = o.getControl();
if (patt0$temp instanceof CyclingControl<?> cycler) {
name = name + " " + Arrays.stream(cycler.getNames()).map(ITextComponent::getFormattedText).collect(Collectors.joining(" "));
}
return name;
});
this.selectedOptions = new HashSet(fuzzy);
}
this.mainScreen.rebuildUI();
}
void erase(int offset) {
if (!Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) && !Keyboard.isKeyDown(Keyboard.KEY_RCONTROL)) {
this.eraseCharacters(offset);
} else {
this.eraseWords(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 {
int i = this.getCursorPosWithOffset(characterOffset);
int j = Math.min(i, this.selectionStart);
int k = Math.max(i, this.selectionStart);
if (j != k) {
String string = (new StringBuilder(this.text)).delete(j, k).toString();
if (string != null) {
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;
boolean bl = wordOffset < 0;
int j = Math.abs(wordOffset);
for(int k = 0; k < j; ++k) {
if (!bl) {
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);
}
}
public void moveCursor(int offset) {
this.setCursor(this.getCursorPosWithOffset(offset));
}
private int getCursorPosWithOffset(int offset) {
int newPos = this.selectionStart + offset;
newPos = Math.max(0, Math.min(newPos, this.text.length()));
return newPos;
}
public void setSelectionStart(int cursor) {
this.selectionStart = Math.clamp(cursor, 0, this.text.length());
}
public void setCursorToStart() {
this.setCursor(0);
}
public void setCursorToEnd() {
this.setCursor(this.text.length());
}
public void setSelectionEnd(int index) {
int i = this.text.length();
this.selectionEnd = Math.clamp(index, 0, i);
FontRenderer textRenderer = Minecraft.getMinecraft().fontRenderer;
if (textRenderer != null) {
if (this.firstCharacterIndex > i) {
this.firstCharacterIndex = i;
}
int j = this.innerWidth;
String string = textRenderer.trimStringToWidth(this.text.substring(this.firstCharacterIndex), j);
int k = string.length() + this.firstCharacterIndex;
if (this.selectionEnd == this.firstCharacterIndex) {
this.firstCharacterIndex -= 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 = Math.clamp(this.firstCharacterIndex, 0, i);
}
}
public static String filterText(String text) {
StringBuilder sb = new StringBuilder();
for(char c : text.toCharArray()) {
if (ChatAllowedCharacters.isAllowedCharacter(c)) {
sb.append(c);
}
}
return sb.toString();
}
}
@@ -0,0 +1,67 @@
package org.taumc.celeritas.impl.gui.frame.tab;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.Style;
import org.taumc.celeritas.api.options.OptionIdentifier;
import org.taumc.celeritas.api.options.structure.Option;
import org.taumc.celeritas.api.options.structure.OptionPage;
import org.taumc.celeritas.impl.gui.frame.AbstractFrame;
import org.taumc.celeritas.impl.gui.frame.OptionPageFrame;
import org.taumc.celeritas.impl.gui.frame.ScrollableFrame;
import org.taumc.celeritas.impl.util.ComponentUtil;
import org.taumc.celeritas.impl.util.Dim2i;
import org.taumc.celeritas.impl.util.PlatformUtil;
public record Tab<T extends AbstractFrame>(OptionIdentifier<Void> id, ITextComponent title, Supplier<Boolean> onSelectFunction, Function<Dim2i, T> frameFunction) {
static ITextComponent idComponent(String namespace) {
return ComponentUtil.literal(PlatformUtil.getModName(namespace)).setStyle((new Style()).setBold(true));
}
public static Tab.Builder<?> createBuilder() {
return new Tab.Builder<>();
}
public Function<Dim2i, T> getFrameFunction() {
return this.frameFunction;
}
public static class Builder<T extends AbstractFrame> {
private ITextComponent title;
private OptionIdentifier<Void> id;
private Function<Dim2i, T> frameFunction = (d) -> null;
private Supplier<Boolean> onSelectFunction = () -> true;
public Builder<T> setTitle(ITextComponent title) {
this.title = title;
return this;
}
public Builder<T> setFrameFunction(Function<Dim2i, T> frameFunction) {
this.frameFunction = frameFunction;
return this;
}
public Builder<T> setOnSelectFunction(Supplier<Boolean> onSelectFunction) {
this.onSelectFunction = onSelectFunction;
return this;
}
public Builder<T> setId(OptionIdentifier<Void> id) {
this.id = id;
return this;
}
public Tab<T> build() {
return new Tab<T>(this.id, this.title, this.onSelectFunction, this.frameFunction);
}
public Tab<ScrollableFrame> from(OptionPage page, Predicate<Option<?>> optionFilter, AtomicReference<Integer> verticalScrollBarOffset) {
Function<Dim2i, ScrollableFrame> frameFunction = (dim2i) -> ScrollableFrame.createBuilder().setDimension(dim2i).setFrame(OptionPageFrame.createBuilder().setDimension(new Dim2i(dim2i.x(), dim2i.y(), dim2i.width(), dim2i.height())).setOptionPage(page).setOptionFilter(optionFilter).build()).setVerticalScrollBarOffset(verticalScrollBarOffset).build();
return (new Builder<ScrollableFrame>()).setTitle(page.getName()).setId(page.getId()).setFrameFunction(frameFunction).build();
}
}
}
@@ -0,0 +1,240 @@
package org.taumc.celeritas.impl.gui.frame.tab;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import net.minecraft.util.text.ITextComponent;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.gui.widgets.AbstractWidget;
import org.taumc.celeritas.impl.gui.widgets.FlatButtonWidget;
import org.taumc.celeritas.impl.util.Dim2i;
import org.apache.commons.lang3.Validate;
import org.taumc.celeritas.impl.gui.frame.AbstractFrame;
import org.taumc.celeritas.impl.gui.frame.ScrollableFrame;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Stream;
public class TabFrame extends AbstractFrame {
private static final int TAB_OPTION_INDENT = 5;
private final Dim2i tabSection;
private final Dim2i frameSection;
private final Multimap<String, Tab<?>> tabs;
private final Runnable onSetTab;
private final AtomicReference<ITextComponent> tabSectionSelectedTab;
private final AtomicReference<Integer> tabSectionScrollBarOffset;
private Tab<?> selectedTab;
private AbstractFrame selectedFrame;
private final Dim2i tabSectionInner;
private ScrollableFrame sidebarFrame;
public TabFrame(Dim2i dim, boolean renderOutline, Multimap<String, Tab<?>> tabs, Runnable onSetTab, AtomicReference<ITextComponent> tabSectionSelectedTab, AtomicReference<Integer> tabSectionScrollBarOffset) {
super(dim, renderOutline);
this.tabs = ImmutableListMultimap.copyOf(tabs);
int tabSectionY = (this.tabs.size() + this.tabs.keySet().size()) * 18;
Optional<Integer> result = Stream.concat(
tabs.keys().stream().map(id -> this.getStringWidth(Tab.idComponent(id)) + 10),
tabs.values().stream().map(tab -> this.getStringWidth(tab.title()) + TAB_OPTION_INDENT)
).max(Integer::compareTo);
this.tabSection = new Dim2i(this.dim.x(), this.dim.y(), result.map(integer -> integer + (24)).orElseGet(() -> (int) (this.dim.width() * 0.35D)), this.dim.height());
this.tabSectionInner = tabSectionY > this.dim.height() ? this.tabSection.withHeight(tabSectionY) : this.tabSection;
this.frameSection = new Dim2i(this.tabSection.getLimitX(), this.dim.y(), this.dim.width() - this.tabSection.width(), this.dim.height());
this.onSetTab = onSetTab;
this.tabSectionSelectedTab = tabSectionSelectedTab;
this.tabSectionScrollBarOffset = tabSectionScrollBarOffset;
if (this.tabSectionSelectedTab.get() != null) {
this.selectedTab = this.tabs.values().stream().filter(tab -> tab.title().getFormattedText().equals(this.tabSectionSelectedTab.get().getFormattedText())).findAny().orElse(null);
}
this.buildFrame();
// Let's build each frame, future note for anyone: do not move this line.
this.tabs.values().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.title());
if (this.onSetTab != null) {
this.onSetTab.run();
}
this.buildFrame();
}
class TabSidebarFrame extends AbstractFrame {
TabSidebarFrame(Dim2i dim) {
super(dim, false);
}
@Override
public void buildFrame() {
this.children.clear();
this.drawable.clear();
this.controlElements.clear();
rebuildTabs();
super.buildFrame();
}
private void rebuildTabs() {
int offsetY = 0;
int width = tabSection.width() - 4;
int height = 18;
for (var modEntry : tabs.asMap().entrySet()) {
// Add a "button" as the header
Dim2i modHeaderDim = new Dim2i(0, offsetY, width, height).withParentOffset(tabSection);
offsetY += height;
TabHeaderWidget headerButton = new TabHeaderWidget(modHeaderDim, modEntry.getKey());
headerButton.setLeftAligned(true);
this.children.add(headerButton);
for (Tab<?> tab : modEntry.getValue()) {
// Add the button for the mod itself
Dim2i tabDim = new Dim2i(0, offsetY, width, height).withParentOffset(tabSection);
FlatButtonWidget button = new FlatButtonWidget(tabDim, tab.title(), () -> {
if (tab.onSelectFunction().get()) {
TabFrame.this.setTab(tab);
}
}) {
@Override
protected int getLeftAlignedTextOffset() {
return TAB_OPTION_INDENT + super.getLeftAlignedTextOffset();
}
};
button.setSelected(TabFrame.this.selectedTab == tab);
button.setLeftAligned(true);
this.children.add(button);
offsetY += height;
}
}
}
}
@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.values().iterator().next();
}
}
this.sidebarFrame = ScrollableFrame.createBuilder()
.setDimension(this.tabSection)
.setFrame(new TabSidebarFrame(this.tabSectionInner))
.setVerticalScrollBarOffset(this.tabSectionScrollBarOffset)
.build();
this.children.add(this.sidebarFrame);
this.rebuildTabFrame();
super.buildFrame();
}
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);
}
}
@Override
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) {
for (AbstractWidget widget : this.children) {
if (widget != this.selectedFrame) {
widget.render(drawContext, mouseX, mouseY, delta);
}
}
if (this.selectedFrame != null) {
this.selectedFrame.render(drawContext, mouseX, mouseY, delta);
}
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
return (this.dim.containsCursor(mouseX, mouseY) && super.mouseClicked(mouseX, mouseY, button));
}
@Override
public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) {
return super.mouseDragged(mouseX, mouseY, button, deltaX, deltaY);
}
@Override
public boolean mouseReleased(double mouseX, double mouseY, int button) {
return super.mouseReleased(mouseX, mouseY, button);
}
@Override
public boolean mouseScrolled(double mouseX, double mouseY, double verticalAmount) {
return super.mouseScrolled(mouseX, mouseY, verticalAmount);
}
public static class Builder {
private final Multimap<String, Tab<?>> functions = MultimapBuilder.linkedHashKeys().arrayListValues().build();
private Dim2i dim;
private boolean renderOutline;
private Runnable onSetTab;
private AtomicReference<ITextComponent> 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<Multimap<String, Tab<?>>> tabs) {
tabs.accept(this.functions);
return this;
}
public Builder onSetTab(Runnable onSetTab) {
this.onSetTab = onSetTab;
return this;
}
public Builder setTabSectionSelectedTab(AtomicReference<ITextComponent> 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,40 @@
package org.taumc.celeritas.impl.gui.frame.tab;
import java.util.Objects;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.gui.widgets.FlatButtonWidget;
import org.taumc.celeritas.impl.loader.common.ModLogoUtil;
import org.taumc.celeritas.impl.util.Dim2i;
import org.taumc.celeritas.impl.util.ResourceLocationUtil;
public class TabHeaderWidget extends FlatButtonWidget {
private static final ResourceLocation FALLBACK_LOCATION = ResourceLocationUtil.make("textures/misc/unknown_pack.png");
private final ResourceLocation logoTexture;
public TabHeaderWidget(Dim2i dim, String modId) {
super(dim, Tab.idComponent(modId), () -> {
});
this.logoTexture = ModLogoUtil.registerLogo(modId);
}
@Override
protected int getLeftAlignedTextOffset() {
return super.getLeftAlignedTextOffset() + Minecraft.getMinecraft().fontRenderer.FONT_HEIGHT;
}
@Override
protected boolean isHovered(int mouseX, int mouseY) {
return false;
}
@Override
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) {
super.render(drawContext, mouseX, mouseY, delta);
ResourceLocation icon = Objects.requireNonNullElse(this.logoTexture, FALLBACK_LOCATION);
int fontHeight = Minecraft.getMinecraft().fontRenderer.FONT_HEIGHT;
int imgY = this.dim.getCenterY() - fontHeight / 2;
drawContext.blit(icon, this.dim.x() + 5, imgY, 0.0F, 0.0F, fontHeight, fontHeight, fontHeight, fontHeight);
}
}
@@ -0,0 +1,7 @@
package org.taumc.celeritas.impl.gui.options;
import net.minecraft.util.text.ITextComponent;
public interface TextProvider {
ITextComponent getLocalizedName();
}
@@ -0,0 +1,30 @@
package org.taumc.celeritas.impl.gui.options.storage;
import java.io.IOException;
import org.taumc.celeritas.CeleritasVintage;
import org.taumc.celeritas.api.options.structure.OptionStorage;
import org.taumc.celeritas.impl.gui.SodiumGameOptions;
public class SodiumOptionsStorage implements OptionStorage<SodiumGameOptions> {
private final SodiumGameOptions options;
public SodiumOptionsStorage() {
this.options = CeleritasVintage.options();
}
@Override
public SodiumGameOptions getData() {
return this.options;
}
@Override
public void save() {
try {
this.options.writeChanges();
} catch (IOException e) {
throw new RuntimeException("Couldn't save configuration changes", e);
}
CeleritasVintage.logger().info("Flushed changes to Embeddium configuration");
}
}
@@ -0,0 +1,5 @@
package org.taumc.celeritas.impl.gui.theme;
public class DefaultColors {
public static final int ELEMENT_ACTIVATED = 0xFF00CBCB;
}
@@ -0,0 +1,79 @@
package org.taumc.celeritas.impl.gui.widgets;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.init.SoundEvents;
import net.minecraft.util.text.ITextComponent;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.gui.compat.Renderable;
import org.taumc.celeritas.impl.gui.compat.Element;
public abstract class AbstractWidget implements Renderable, Element {
protected final FontRenderer font;
protected boolean focused;
protected boolean hovered;
protected AbstractWidget() {
this.font = Minecraft.getMinecraft().fontRenderer;
}
public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) {
}
protected void drawString(GuiGraphics drawContext, String str, int x, int y, int color) {
drawContext.drawString(this.font, str, x, y, color);
}
protected void drawString(GuiGraphics drawContext, ITextComponent text, int x, int y, int color) {
drawContext.drawString(this.font, text, x, y, color);
}
public boolean isHovered() {
return this.hovered;
}
protected void drawRect(GuiGraphics drawContext, int x1, int y1, int x2, int y2, int color) {
drawContext.fill(x1, y1, x2, y2, color);
}
protected void playClickSound() {
Minecraft.getMinecraft().getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(SoundEvents.UI_BUTTON_CLICK, 1.0F));
}
protected int getStringWidth(String text) {
return this.font.getStringWidth(text);
}
protected int getStringWidth(ITextComponent text) {
return this.font.getStringWidth(text.getFormattedText());
}
public static List<String> split(String string, int width) {
return Minecraft.getMinecraft().fontRenderer.listFormattedStringToWidth(string, width);
}
public static List<String> split(ITextComponent component, int width) {
return split(component.getFormattedText(), width);
}
public boolean isFocused() {
return this.focused;
}
public void setFocused(boolean focused) {
this.focused = focused;
}
protected static boolean keySelected(int keyCode) {
return keyCode == 57 || keyCode == 28;
}
protected void drawBorder(GuiGraphics drawContext, int x1, int y1, int x2, int y2, int color) {
drawContext.fill(x1, y1, x2, y1 + 1, color);
drawContext.fill(x1, y2 - 1, x2, y2, color);
drawContext.fill(x1, y1, x1 + 1, y2, color);
drawContext.fill(x2 - 1, y1, x2, y2, color);
}
}
@@ -0,0 +1,133 @@
package org.taumc.celeritas.impl.gui.widgets;
import java.util.Objects;
import net.minecraft.util.text.ITextComponent;
import org.jetbrains.annotations.NotNull;
import org.taumc.celeritas.impl.gui.compat.GuiGraphics;
import org.taumc.celeritas.impl.gui.theme.DefaultColors;
import org.taumc.celeritas.impl.util.Dim2i;
public class FlatButtonWidget extends AbstractWidget {
protected final Dim2i dim;
private final Runnable action;
private @NotNull Style style = FlatButtonWidget.Style.defaults();
private boolean selected;
private boolean enabled = true;
private boolean visible = true;
private boolean leftAligned;
private ITextComponent label;
public FlatButtonWidget(Dim2i dim, ITextComponent label, Runnable action) {
this.dim = dim;
this.label = label;
this.action = action;
}
protected int getLeftAlignedTextOffset() {
return 10;
}
protected boolean isHovered(int mouseX, int mouseY) {
return this.dim.containsCursor(mouseX, mouseY);
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (!this.enabled || !this.visible) {
return false;
}
if (button == 0 && this.dim.containsCursor(mouseX, mouseY)) {
this.action.run();
this.playClickSound();
return true;
}
return false;
}
@Override
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) {
if (this.visible) {
this.hovered = this.isHovered(mouseX, mouseY);
int backgroundColor = this.enabled ? (this.hovered ? this.style.bgHovered : this.style.bgDefault) : this.style.bgDisabled;
int textColor = this.enabled ? this.style.textDefault : this.style.textDisabled;
int strWidth = this.getStringWidth(this.label);
this.drawRect(drawContext, this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), backgroundColor);
int textX;
if (this.leftAligned) {
textX = this.dim.x() + this.getLeftAlignedTextOffset();
} else {
textX = this.dim.getCenterX() - strWidth / 2;
}
this.drawString(drawContext, this.label, textX, this.dim.getCenterY() - 4, textColor);
if (this.enabled && this.selected) {
this.drawRect(drawContext, this.dim.x(), this.leftAligned ? this.dim.y() : this.dim.getLimitY() - 1, this.leftAligned ? this.dim.x() + 1 : this.dim.getLimitX(), this.dim.getLimitY(), DefaultColors.ELEMENT_ACTIVATED);
}
}
}
public void setStyle(@NotNull Style style) {
Objects.requireNonNull(style);
this.style = style;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public void setLeftAligned(boolean leftAligned) {
this.leftAligned = leftAligned;
}
private void doAction() {
this.action.run();
this.playClickSound();
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public void setLabel(ITextComponent text) {
this.label = text;
}
public ITextComponent getLabel() {
return this.label;
}
public Dim2i getDimensions() {
return this.dim;
}
@Override
public boolean isMouseOver(double mouseX, double mouseY) {
return this.dim.containsCursor(mouseX, mouseY);
}
public static class Style {
public int bgHovered;
public int bgDefault;
public int bgDisabled;
public int textDefault;
public int textDisabled;
public static Style defaults() {
Style style = new Style();
style.bgHovered = 0xE0202020;
style.bgDefault = 0x90000000;
style.bgDisabled = 0x60000000;
style.textDefault = 0xFFFFFFFF;
style.textDisabled = 0x90FFFFFF;
return style;
}
}
}
@@ -0,0 +1,40 @@
package org.taumc.celeritas.impl.loader.common;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import org.taumc.celeritas.CeleritasVintage;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class ModLogoUtil {
private static final Set<String> erroredLogos = new HashSet<>();
public static ResourceLocation registerLogo(String modId) {
if (erroredLogos.contains(modId)) return null;
ModContainer container = Loader.instance().getIndexedModList().get(modId);
if (container == null) return null;
String logoPath;
if (modId.equals("celeritas")) {
logoPath = "textures/gui/icon.png";
} else {
logoPath = "icon.png";
}
ResourceLocation location = new ResourceLocation(modId, logoPath);
try {
Minecraft.getMinecraft().getResourceManager().getResource(location);
return location;
} catch (IOException e) {
erroredLogos.add(modId);
CeleritasVintage.logger().error("Exception reading logo for " + modId, e);
return null;
}
}
}
@@ -15,6 +15,7 @@ import org.embeddedt.embeddium.impl.render.chunk.ChunkRenderMatrices;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderFogComponent;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
import org.embeddedt.embeddium.impl.render.terrain.SimpleWorldRenderer;
import org.joml.Matrix4f;
import org.taumc.celeritas.CeleritasVintage;
@@ -54,7 +55,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Vin
@Override
protected VintageRenderSectionManager createRenderSectionManager(CommandList commandList) {
return VintageRenderSectionManager.create(ChunkMeshFormats.VANILLA_LIKE, this.world, this.getEffectiveRenderDistance(), commandList);
return VintageRenderSectionManager.create(chooseVertexType(), this.world, this.getEffectiveRenderDistance(), commandList);
}
/**
@@ -116,6 +117,10 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Vin
* @return True if the entity is visible, otherwise false
*/
public boolean isEntityVisible(Entity entity) {
if (!CeleritasVintage.options().performance.useEntityCulling || this.renderSectionManager.isInShadowPass()) {
return true;
}
// Ensure entities with outlines or nametags are always visible
if (entity.isGlowing() || entity.getAlwaysRenderNameTagForRender()) {
return true;
@@ -128,4 +133,12 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Vin
return this.isBoxVisible(box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ);
}
private ChunkVertexType chooseVertexType() {
if (!CeleritasVintage.options().performance.useCompactVertexFormat) {
return ChunkMeshFormats.VANILLA_LIKE;
}
return ChunkMeshFormats.COMPACT;
}
}
@@ -56,7 +56,7 @@ public class VintageRenderPassConfigurationBuilder {
.name("translucent")
.fragmentDiscard(false)
.useReverseOrder(true)
.useTranslucencySorting(true) // TODO allow disabling
.useTranslucencySorting(CeleritasVintage.options().performance.useTranslucentFaceSorting)
.build();
ImmutableListMultimap.Builder<BlockRenderLayer, TerrainRenderPass> vanillaRenderStages = ImmutableListMultimap.builder();
@@ -69,9 +69,23 @@ public class VintageRenderPassConfigurationBuilder {
vanillaRenderStages.put(BlockRenderLayer.SOLID, solidPass);
vanillaRenderStages.put(BlockRenderLayer.TRANSLUCENT, translucentPass);
vanillaRenderStages.put(BlockRenderLayer.SOLID, cutoutMippedPass);
if (CeleritasVintage.options().performance.useRenderPassConsolidation) {
cutoutMaterial = new Material(cutoutMippedPass, AlphaCutoffParameter.ONE_TENTH, false);
vanillaRenderStages.put(BlockRenderLayer.SOLID, cutoutMippedPass);
} else {
TerrainRenderPass cutoutPass;
cutoutPass = builderForRenderType(BlockRenderLayer.CUTOUT, vertexType)
.name("cutout")
.fragmentDiscard(true)
.useReverseOrder(false)
.build();
cutoutMaterial = new Material(cutoutPass, AlphaCutoffParameter.ONE_TENTH, false);
vanillaRenderStages.put(BlockRenderLayer.CUTOUT, cutoutPass);
vanillaRenderStages.put(BlockRenderLayer.CUTOUT_MIPPED, cutoutMippedPass);
}
// Now build the material map
Map<BlockRenderLayer, Material> renderTypeToMaterialMap = new Reference2ReferenceOpenHashMap<>(4,
@@ -19,6 +19,7 @@ import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.util.position.SectionPos;
import org.jetbrains.annotations.Nullable;
import org.taumc.celeritas.CeleritasVintage;
import org.taumc.celeritas.impl.render.terrain.compile.VintageChunkBuildContext;
import org.taumc.celeritas.impl.render.terrain.compile.task.ChunkBuilderMeshingTask;
import org.taumc.celeritas.impl.render.terrain.sprite.SpriteUtil;
@@ -31,20 +32,19 @@ public class VintageRenderSectionManager extends RenderSectionManager {
@Getter
private final ClonedChunkSectionCache sectionCache;
public VintageRenderSectionManager(RenderPassConfiguration<?> configuration, WorldClient world, int renderDistance, CommandList commandList, int minSection, int maxSection, int requestedThreads) {
super(configuration, () -> new VintageChunkBuildContext(world, configuration), ChunkRenderer::new, renderDistance, commandList, minSection, maxSection, requestedThreads);
public VintageRenderSectionManager(RenderPassConfiguration<?> configuration, WorldClient world, int renderDistance, CommandList commandList, int minSection, int maxSection) {
super(configuration, () -> new VintageChunkBuildContext(world, configuration), ChunkRenderer::new, renderDistance, commandList, minSection, maxSection, CeleritasVintage.options().performance.chunkBuilderThreads);
this.world = world;
this.sectionCache = new ClonedChunkSectionCache(world);
}
public static VintageRenderSectionManager create(ChunkVertexType vertexType, WorldClient world, int renderDistance, CommandList commandList) {
// TODO support thread option
return new VintageRenderSectionManager(VintageRenderPassConfigurationBuilder.build(vertexType), world, renderDistance, commandList, 0, 16, 0);
return new VintageRenderSectionManager(VintageRenderPassConfigurationBuilder.build(vertexType), world, renderDistance, commandList, 0, 16);
}
@Override
protected AsyncOcclusionMode getAsyncOcclusionMode() {
return AsyncOcclusionMode.EVERYTHING;
return CeleritasVintage.options().performance.asyncOcclusionMode;
}
@Override
@@ -54,7 +54,7 @@ public class VintageRenderSectionManager extends RenderSectionManager {
@Override
protected boolean useFogOcclusion() {
return true;
return CeleritasVintage.options().performance.useFogOcclusion;
}
@Override
@@ -99,7 +99,7 @@ public class VintageRenderSectionManager extends RenderSectionManager {
@Override
protected boolean allowImportantRebuilds() {
return false;
return !CeleritasVintage.options().performance.alwaysDeferChunkUpdates;
}
@Override
@@ -125,6 +125,11 @@ public class VintageRenderSectionManager extends RenderSectionManager {
super(device, renderPassConfiguration);
}
@Override
public boolean useBlockFaceCulling(){
return CeleritasVintage.options().performance.useBlockFaceCulling;
}
@Override
protected void configureShaderInterface(ChunkShaderInterface shader) {
shader.setTextureSlot(ChunkShaderTextureSlot.BLOCK, 0);
@@ -20,6 +20,7 @@ import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncode
import org.embeddedt.embeddium.impl.util.QuadUtil;
import org.lwjgl.opengl.GL11C;
import org.lwjgl.system.MemoryUtil;
import org.taumc.celeritas.CeleritasVintage;
import org.taumc.celeritas.impl.extensions.SpriteExtension;
import org.taumc.celeritas.impl.extensions.TextureMapExtension;
import org.taumc.celeritas.impl.world.WorldSlice;
@@ -37,12 +38,14 @@ public class VintageChunkBuildContext extends ChunkBuildContext {
@Getter
private final WorldSlice worldSlice;
private final RenderPassConfiguration<?> renderPassConfiguration;
private final boolean useRenderPassOptimization;
public VintageChunkBuildContext(WorldClient world, RenderPassConfiguration renderPassConfiguration) {
super(renderPassConfiguration);
this.renderPassConfiguration = renderPassConfiguration;
this.worldSlice = new WorldSlice(world);
this.textureAtlas = (TextureMapExtension) Minecraft.getMinecraft().getTextureMapBlocks();
this.useRenderPassOptimization = CeleritasVintage.options().performance.useRenderPassOptimization;
}
public void setupTranslation(int x, int y, int z) {
@@ -94,7 +97,7 @@ public class VintageChunkBuildContext extends ChunkBuildContext {
}
private Material selectMaterial(Material material, TextureAtlasSprite sprite) {
if (sprite != null && sprite.getClass() == TextureAtlasSprite.class && !sprite.hasAnimationMetadata()) {
if (sprite != null && sprite.getClass() == TextureAtlasSprite.class && !sprite.hasAnimationMetadata() && this.useRenderPassOptimization) {
var transparencyLevel = ((SpriteExtension)sprite).celeritas$getTransparencyLevel();
if (transparencyLevel == SpriteTransparencyLevel.OPAQUE) {
// Downgrade to solid
@@ -0,0 +1,20 @@
package org.taumc.celeritas.impl.util;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
public class ComponentUtil {
public static ITextComponent empty() {
return new TextComponentString("");
}
public static ITextComponent literal(String text) {
return new TextComponentString(text);
}
public static ITextComponent translatable(String key, Object... args) {
return new TextComponentTranslation(key, args);
}
}
@@ -0,0 +1,51 @@
package org.taumc.celeritas.impl.util;
public record Dim2i(int x, int y, int width, int height) implements Point2i {
public int getLimitX() {
return this.x + this.width;
}
public int getLimitY() {
return this.y + this.height;
}
public boolean containsCursor(double x, double y) {
return x >= this.x && x < this.getLimitX() && y >= this.y && y < this.getLimitY();
}
public int getCenterX() {
return this.x + (this.width / 2);
}
public int getCenterY() {
return this.y + (this.height / 2);
}
public Dim2i withHeight(int newHeight) {
return new Dim2i(x, y, width, newHeight);
}
public Dim2i withWidth(int newWidth) {
return new Dim2i(x, y, newWidth, height);
}
public Dim2i withX(int newX) {
return new Dim2i(newX, y, width, height);
}
public Dim2i withY(int newY) {
return new Dim2i(x, newY, width, height);
}
public boolean canFitDimension(Dim2i anotherDim) {
return this.x() <= anotherDim.x() && this.y() <= anotherDim.y() && this.getLimitX() >= anotherDim.getLimitX() && this.getLimitY() >= anotherDim.getLimitY();
}
public boolean overlapsWith(Dim2i other) {
return this.x() < other.getLimitX() && this.getLimitX() > other.x() && this.y() < other.getLimitY() && this.getLimitY() > other.y();
}
public Dim2i withParentOffset(Point2i parent) {
return new Dim2i(parent.x() + x, parent.y() + y, width, height);
}
}
@@ -0,0 +1,30 @@
package org.taumc.celeritas.impl.util;
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.common.Loader;
import java.io.File;
public class PlatformUtil {
public static boolean isLoadValid() {
//TODO Implement. Doesn't seem to be used outside of shaders
return true;
}
public static boolean modPresent(String modid) {
return Loader.isModLoaded(modid);
}
public static String getModName(String modId) {
return Loader.instance().getIndexedModList().get(modId).getName();
}
public static File getConfigDir() {
return Loader.instance().getConfigDir();
}
public static File getGameDir() {
return Minecraft.getMinecraft().gameDir;
}
}
@@ -0,0 +1,18 @@
package org.taumc.celeritas.impl.util;
public interface Point2i {
Point2i ZERO = new Point2i() {
@Override
public int x() {
return 0;
}
@Override
public int y() {
return 0;
}
};
int x();
int y();
}
@@ -0,0 +1,14 @@
package org.taumc.celeritas.impl.util;
import net.minecraft.util.ResourceLocation;
public class ResourceLocationUtil {
public static ResourceLocation make(String namespace, String path) {
return new ResourceLocation(namespace, path);
}
public static ResourceLocation make(String str) {
return new ResourceLocation(str);
}
}
@@ -0,0 +1,67 @@
package org.taumc.celeritas.impl.util;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
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 <T> List<T> fuzzySearch(Iterable<T> options, String userInput, int maxDistance, Function<T, String> toStringFn) {
List<T> result = new ArrayList<>();
String[] targetWords = userInput.toLowerCase().split("\\s+");
for (T option : options) {
String sentence = toStringFn.apply(option).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,12 +1,54 @@
package org.taumc.celeritas.mixin.core;
import it.unimi.dsi.fastutil.longs.LongArrayFIFOQueue;
import net.minecraft.client.Minecraft;
import org.lwjgl.opengl.GL32C;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.taumc.celeritas.CeleritasVintage;
@Mixin(Minecraft.class)
public class MinecraftMixin {
@Unique
private final LongArrayFIFOQueue fences = new LongArrayFIFOQueue();
@Inject(method = "runTick", at = @At("HEAD"))
private void preRender(CallbackInfo ci) {
while (this.fences.size() > CeleritasVintage.options().advanced.cpuRenderAheadLimit) {
var fence = this.fences.dequeueLong();
// We do a ClientWaitSync here instead of a WaitSync to not allow the CPU to get too far ahead of the GPU.
// This is also needed to make sure that our persistently-mapped staging buffers function correctly, rather
// than being overwritten by data meant for future frames before the current one has finished rendering on
// the GPU.
//
// Because we use GL_SYNC_FLUSH_COMMANDS_BIT, a flush will be inserted at some point in the command stream
// (the stream of commands the GPU and/or driver (aka. the "server") is processing).
// In OpenGL 4.4 contexts and below, the flush will be inserted *right before* the call to ClientWaitSync.
// In OpenGL 4.5 contexts and above, the flush will be inserted *right after* the call to FenceSync (the
// creation of the fence).
// The flush, when the server reaches it in the command stream and processes it, tells the server that it
// must *finish execution* of all the commands that have already been processed in the command stream,
// and only after everything before the flush is done is it allowed to start processing and executing
// commands after the flush.
// Because we are also waiting on the client for the FenceSync to finish, the flush is effectively treated
// like a Finish command, where we know that once ClientWaitSync returns, it's likely that everything
// before it has been completed by the GPU.
GL32C.glClientWaitSync(fence, GL32C.GL_SYNC_FLUSH_COMMANDS_BIT, Long.MAX_VALUE);
GL32C.glDeleteSync(fence);
}
}
@Inject(method = "runTick", at = @At("RETURN"))
private void postRender(CallbackInfo ci) {
var fence = GL32C.glFenceSync(GL32C.GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
if (fence == 0) {
throw new RuntimeException("Failed to create fence object");
}
this.fences.enqueue(fence);
}
}
@@ -0,0 +1,18 @@
package org.taumc.celeritas.mixin.features.options;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.settings.GameSettings;
import org.objectweb.asm.Opcodes;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.taumc.celeritas.CeleritasVintage;
@Mixin(EntityRenderer.class)
public class MixinEntityRenderer {
@Redirect(method = "renderRainSnow", at = @At(value = "FIELD", target = "Lnet/minecraft/client/settings/GameSettings;fancyGraphics:Z", opcode = Opcodes.GETFIELD))
private boolean redirectGetFancyWeather(GameSettings instance) {
return CeleritasVintage.options().quality.weatherQuality.isFancy(Minecraft.getMinecraft().gameSettings.fancyGraphics);
}
}
@@ -0,0 +1,16 @@
package org.taumc.celeritas.mixin.features.options;
import net.minecraftforge.client.GuiIngameForge;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.taumc.celeritas.CeleritasVintage;
@Mixin(GuiIngameForge.class)
public class MixinGuiIngameForge {
@Redirect(method = "renderGameOverlay", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;isFancyGraphicsEnabled()Z"))
private boolean celeritas$redirectVignette() {
return CeleritasVintage.options().quality.enableVignette;
}
}
@@ -0,0 +1,25 @@
package org.taumc.celeritas.mixin.features.options;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiOptions;
import net.minecraft.client.gui.GuiScreen;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.taumc.celeritas.impl.gui.CeleritasVideoOptionsScreen;
@Mixin(GuiOptions.class)
public class MixinGuiOptions extends GuiScreen {
@Dynamic
@Inject(method = "actionPerformed", at = @At("HEAD"), cancellable = true)
private void open(GuiButton button, CallbackInfo ci) {
if(button.enabled && button.id == 101) {
this.mc.displayGuiScreen(new CeleritasVideoOptionsScreen(this));
ci.cancel();
}
}
}
@@ -14,6 +14,7 @@ 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 org.taumc.celeritas.CeleritasVintage;
import org.taumc.celeritas.impl.extensions.SpriteExtension;
import org.taumc.celeritas.impl.extensions.TextureMapExtension;
@@ -53,6 +54,10 @@ public class TextureAtlasMixin implements TextureMapExtension {
@ModifyExpressionValue(method = "updateAnimations", at = @At(value = "INVOKE", target = "Ljava/util/List;iterator()Ljava/util/Iterator;"))
private Iterator<TextureAtlasSprite> getFilteredIterator(Iterator<TextureAtlasSprite> iterator) {
if (CeleritasVintage.options().performance.animateOnlyVisibleTextures) {
return Iterators.filter(iterator, sprite -> ((SpriteExtension)sprite).celeritas$shouldUpdate());
} else {
return iterator;
}
}
}
@@ -0,0 +1,82 @@
#PARSE_ESCAPES
celeritas.conflicting_mod=Celeritas detected the presence of mods that are known to cause rendering issues/crashes. It is recommended to uninstall them. See the list below.
celeritas.conflicting_mod_list=[{2}]
celeritas.search_bar_empty=Search options...
celeritas.options.added_by_mod_string=Added by mod: %s
celeritas.options.fullscreen.resolution.tooltip=Controls the resolution of the game in fullscreen mode.
celeritas.options.use_quad_normals_for_lighting.name=Use Accurate Quad Shading
celeritas.options.use_quad_normals_for_lighting.tooltip=When enabled, Celeritas will apply shading to non-vanilla block faces based on the true direction they are facing, not their axis-aligned direction. This can improve lighting quality when the Forge experimental light pipeline is disabled (which is recommended for best performance).\n\nIt has no effect if the experimental light pipeline is enabled.
celeritas.options.use_render_pass_optimization.name=Use Render Pass Optimization
celeritas.options.use_render_pass_optimization.tooltip=When enabled, Celeritas will detect block model faces that are marked as transparent (or translucent) when the texture is actually opaque (or transparent) and automatically use a more optimal render pass for them.\n\nThis optimization has no effect when a shader pack is active.
celeritas.options.use_render_pass_consolidation.name=Use Render Pass Consolidation
celeritas.options.use_render_pass_consolidation.tooltip=Combines some vanilla render passes into a single pass. This can very significantly reduce the total number of draw calls needed to render the world, with no visual impact. However, the total amount of rendered geometry will be the same.
celeritas.options.inactivity_fps_limit.tooltip=Controls how the game limits framerate when inactive. Minimized only limits the framerate if the game is minimized. AFK also limits the framerate if the player is inactive for long enough.
celeritas.options.use_faster_clouds.name=Use Faster Clouds
celeritas.options.use_faster_clouds.tooltip=When enabled, Celeritas replaces vanilla cloud rendering with a less glitchy and potentially faster implementation. Disable this if mods' cloud customizations aren't visible.
celeritas.options.async_graph_search.name=Async Occlusion Culling
celeritas.options.async_graph_search.tooltip=Performs occlusion/frustum culling asynchronously, up to one frame behind the current camera position. This can improve frametimes, particularly at higher render distances, but at the cost of chunks popping into view if the camera is turned too aggressively."
sodium.option_impact.low=Low
sodium.option_impact.medium=Medium
sodium.option_impact.high=High
sodium.option_impact.extreme=Extreme
sodium.option_impact.varies=Varies
sodium.options.pages.quality=Quality
sodium.options.pages.performance=Performance
sodium.options.pages.advanced=Advanced
sodium.options.view_distance.tooltip=The render distance controls how far away terrain will be rendered. Shorter distances mean that less terrain will be rendered improving frame rates.
sodium.options.simulation_distance.tooltip=The simulation distance controls how far away terrain and entities will be loaded and ticked. Shorter distances can reduce the internal server's load and may improve frame rates.
sodium.options.brightness.tooltip=Controls the brightness (gamma) of the game.
sodium.options.gui_scale.tooltip=Sets the maximum scale factor to be used for the user interface. If 'auto' is used then the largest scale factor will always be used.
sodium.options.fullscreen.tooltip=If enabled the game will display in full-screen (if supported).
sodium.options.v_sync.tooltip=If enabled the game's frame rate will be synchronized to the monitor's refresh rate making for a generally smoother experience at the expense of overall input latency. This setting might reduce performance if your system is too slow.
sodium.options.fps_limit.tooltip=Limits the maximum number of frames per second. This can help reduce battery usage and general system load when multi-tasking. If VSync is enabled this option will be ignored unless it is lower than your display's refresh rate.
sodium.options.view_bobbing.tooltip=If enabled the player's view will sway and bob when moving around. Players who experience motion sickness while playing can benefit from disabling this.
sodium.options.attack_indicator.tooltip=Controls where the Attack Indicator is displayed on screen.
sodium.options.autosave_indicator.tooltip=If enabled an indicator will be shown when the game is saving the world to disk.
sodium.options.graphics_quality.tooltip=The default graphics quality controls some legacy options and is necessary for mod compatibility. If the options below are left to \Default\ they will use this setting.
sodium.options.clouds_quality.tooltip=Controls the presence of rendered clouds in the sky.
sodium.options.weather_quality.tooltip=Controls the quality of rain and snow effects.
sodium.options.leaves_quality.name=Leaves
sodium.options.leaves_quality.tooltip=Controls the quality of leaves.
sodium.options.particle_quality.tooltip=Controls the maximum number of particles which can be present on screen at any one time.
sodium.options.smooth_lighting.tooltip=Controls whether blocks will be smoothly lit and shaded. This slightly increases the amount of time needed to re-build a chunk but doesn't affect frame rates.
sodium.options.biome_blend.value=%s block(s)
sodium.options.biome_blend.tooltip=Controls the range which biomes will be sampled for block colorization. Higher values greatly increase the amount of time it takes to build chunks for diminishing improvements in quality.
sodium.options.entity_distance.tooltip=Controls how far away entities can render from the player. Higher values increase the render distance at the expense of frame rates.
sodium.options.entity_shadows.tooltip=If enabled basic shadows will be rendered beneath mobs and other entities.
sodium.options.vignette.name=Vignette
sodium.options.vignette.tooltip=If enabled a vignette effect will be rendered on the player's view. This is very unlikely to make a difference to frame rates unless you are fill-rate limited.
sodium.options.mipmap_levels.tooltip=Controls the number of mipmaps which will be used for block model textures. Higher values provide better rendering of blocks in the distance but may adversely affect performance with many animated textures.
sodium.options.use_block_face_culling.name=Use Block Face Culling
sodium.options.use_block_face_culling.tooltip=If enabled only the sides of blocks which are facing the camera will be submitted for rendering. This can eliminate a large number of block faces very early in the rendering process saving memory bandwidth and time on the GPU. Some resource packs may have issues with this option so try disabling it if you're seeing holes in blocks.
sodium.options.use_compact_vertex_format.name=Use Compact Vertex Format
sodium.options.use_compact_vertex_format.tooltip=If enabled a more compact vertex format will be used for rendering chunks. This can reduce graphics memory usage and bandwidth requirements significantly especially for integrated graphics cards but can cause z-fighting with some resource packs due to how it reduces the precision of position and texture coordinate attributes. Disabling this has no effect if Oculus is installed.
sodium.options.translucent_face_sorting.name=Translucent Face Sorting
sodium.options.translucent_face_sorting.tooltip=If enabled translucent effects from surfaces such as stained glass and water will be applied correctly.
sodium.options.use_fog_occlusion.name=Use Fog Occlusion
sodium.options.use_fog_occlusion.tooltip=If enabled chunks which are determined to be fully hidden by fog effects will not be rendered helping to improve performance. The improvement can be more dramatic when fog effects are heavier (such as while underwater) but it may cause undesirable visual artifacts between the sky and fog in some scenarios.
sodium.options.use_entity_culling.name=Use Entity Culling
sodium.options.use_entity_culling.tooltip=If enabled entities determined not to be in any visible chunks will be skipped during rendering. This can help improve performance by avoiding the rendering of entities located underground or behind walls.
sodium.options.animate_only_visible_textures.name=Animate Only Visible Textures
sodium.options.animate_only_visible_textures.tooltip=If enabled only animated textures determined to be visible will be updated. This can provide a significant boost to frame rates on some hardware especially with heavier resource packs. If you experience issues with some textures not being animated try disabling this option.
sodium.options.cpu_render_ahead_limit.name=CPU Render-Ahead Limit
sodium.options.cpu_render_ahead_limit.tooltip=Specifies the maximum number of frames the CPU can be waiting on the GPU to finish rendering. Very low or high values may create frame rate instability.
sodium.options.cpu_render_ahead_limit.value=%s frame(s)
sodium.options.performance_impact_string=Performance Impact: %s
sodium.options.use_persistent_mapping.name=Use Persistent Mapping
sodium.options.use_persistent_mapping.tooltip=If enabled a small amount of memory will be persistently mapped as a staging buffer for chunk uploading helping to reduce CPU overhead and frame time instability when loading or updating chunks.\n\nRequires OpenGL 4.4 or ARB_buffer_storage.
sodium.options.chunk_update_threads.name=Chunk Update Threads
sodium.options.chunk_update_threads.tooltip=Specifies the number of threads to use for chunk building. Using more threads can speed up chunk loading and update speed but may negatively impact frame times.
sodium.options.always_defer_chunk_updates.name=Always Defer Chunk Updates
sodium.options.always_defer_chunk_updates.tooltip=If enabled rendering will never wait for chunk updates to finish even if they are important. This can greatly improve frame rates in some scenarios but it may create significant visual lag in the world.
sodium.options.use_no_error_context.name=Use No Error Context
sodium.options.use_no_error_context.tooltip=If enabled the OpenGL context will be created with error checking disabled. This may slightly improve performance but it also increases the risk that the game will crash instead of gracefully handling OpenGL errors. You should disable this option if you are experiencing sudden unexplained crashes.
sodium.options.buttons.undo=Undo
sodium.options.buttons.apply=Apply
sodium.options.buttons.donate=Support Sodium!
sodium.console.game_restart=The game must be restarted to apply one or more video settings!
sodium.console.broken_nvidia_driver=Your NVIDIA graphics drivers are out of date!\n* This will cause severe performance issues and crashes when Celeritas is installed.\n* Please update your graphics drivers to the latest version (version 536.23 or newer.)
sodium.console.pojav_launcher=PojavLauncher is not supported when using Celeritas.\n* You are very likely to run into extreme performance issues graphical bugs and crashes.\n* You will be on your own if you decide to continue -- we will not help you with any bugs or crashes!
sodium.console.core_shaders_error=The following resource packs are incompatible with Celeritas:
sodium.console.core_shaders_warn=The following resource packs may be incompatible with Celeritas:
sodium.console.core_shaders_info=Check the game log for detailed information.
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

+6
View File
@@ -0,0 +1,6 @@
{
"pack": {
"description": "${mod_name} Resources",
"pack_format": 2
}
}