Merge pull request 'Remove Blackilykat features, update to 1.21.1' (#1) from chomens into 1.20.2

Reviewed-on: #1
This commit is contained in:
7cc5c4f330d47060 2024-10-12 23:47:42 -04:00
commit 9b5d92c008
78 changed files with 578 additions and 2399 deletions

View file

@ -1,5 +1,5 @@
# ChipmunkMod
My fork of [chipmunkmod (Blackilykat fork)](https://code.chipmunk.land/Blackilykat/chipmunkmod)
My fork of [chipmunkmod (ChomeNS fork)](https://code.chipmunk.land/ChomeNS/chipmunkmod)
If you are not sure if this code is safe to compile and run, you can read through every line of code, and compile it with the below instructions. You can also see the commit history by clicking on the (n) commits button, to make sure nobody has added any exploits or introduced vulnerabilities to the code.
@ -8,9 +8,9 @@ If you find any exploits, security issues, etc in the code, please send me an is
## alexa how to install
This version does not have any releases, so to use this, you will have to compile it.
Make sure you have a Java 17 JDK installed, then run "./gradlew build" for Unix(-like) OSes or "gradlew.bat build" for Windows. If the build was successful, the compiled JAR file should be in "build/libs".
Make sure you have a Java 21 JDK installed, then run "./gradlew build" for Unix(-like) OSes or "gradlew.bat build" for Windows. If the build was successful, the compiled JAR file should be in "build/libs".
Make sure you have the Fabric loader and Fabric API installed for version 1.20.2, and copy the JAR file to your mods folder.
Make sure you have the Fabric loader and Fabric API installed for version 1.21.1, and copy the JAR file to your mods folder.
if thats not clear enough ask your search engine how to install a fabric mod

View file

@ -1,18 +1,33 @@
plugins {
id 'fabric-loom' version '1.2-SNAPSHOT'
id 'fabric-loom' version '1.7-SNAPSHOT'
id 'maven-publish'
}
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
archivesBaseName = project.archives_base_name
version = project.mod_version
group = project.maven_group
dependencies {
implementation 'org.apache.commons:commons-text:1.10.0' // Use the version that best suits your project
repositories {
// Add repositories to retrieve artifacts from in here.
// You should only use this when depending on other mods because
// Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html
// for more information about repositories.
mavenCentral()
}
// https://github.com/MeteorDevelopment/meteor-client/blob/master/build.gradle#L46
configurations {
implementation.extendsFrom(library)
shadow.extendsFrom(library)
include.extendsFrom(library)
}
dependencies {
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
@ -21,22 +36,18 @@ dependencies {
// Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
modImplementation include("net.kyori:adventure-platform-fabric:5.10.0") // for Minecraft 1.20.2
library "net.kyori:adventure-platform-fabric:5.14.1" // for Minecraft 1.21-1.21.1
modImplementation include("net.kyori:adventure-text-serializer-legacy:4.14.0")
library "net.kyori:adventure-text-serializer-gson:4.17.0"
modImplementation include("org.luaj:luaj-jse:3.0.1")
library "net.kyori:adventure-text-serializer-legacy:4.17.0"
library "org.luaj:luaj-jse:3.0.1"
// Uncomment the following line to enable the deprecated Fabric API modules.
// These are included in the Fabric API production distribution and allow you to update your mod to the latest modules at a later more convenient time.
// modImplementation "net.fabricmc.fabric-api:fabric-api-deprecated:${project.fabric_version}"
compileOnly 'org.projectlombok:lombok:1.18.28'
annotationProcessor 'org.projectlombok:lombok:1.18.28'
testCompileOnly 'org.projectlombok:lombok:1.18.28'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.28'
}
processResources {
@ -49,7 +60,14 @@ processResources {
tasks.withType(JavaCompile).configureEach {
// Minecraft 1.18 (1.18-pre2) upwards uses Java 17.
it.options.release = 17
it.options.release = 21
}
java {
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present.
// If you remove this line, sources will not be generated.
withSourcesJar()
}
jar {
@ -57,3 +75,20 @@ jar {
rename { "${it}_${project.archivesBaseName}"}
}
}
// configure the maven publication
publishing {
publications {
mavenJava(MavenPublication) {
from components.java
}
}
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
repositories {
// Add repositories to publish to here.
// Notice: This block does NOT have the same function as the block in the top level.
// The repositories here will be used for publishing your artifact, not for
// retrieving dependencies.
}
}

View file

@ -4,15 +4,15 @@ org.gradle.parallel=true
# Fabric Properties
# check these on https://fabricmc.net/develop
minecraft_version=1.20.2
yarn_mappings=1.20.2+build.1
loader_version=0.14.22
minecraft_version=1.21.1
yarn_mappings=1.21.1+build.3
loader_version=0.16.5
# Mod Properties
mod_version = 1.1.1
mod_version = 2.0.0
maven_group = land.chipmunk.chipmunkmod
archives_base_name = chipmunkmod
# Dependencies
fabric_version=0.89.2+1.20.2
fabric_version=0.105.0+1.21.1

View file

@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME

1
gradlew vendored
View file

@ -122,6 +122,7 @@ if [ -n "$JAVA_HOME" ] ; then
else
JAVACMD=$JAVA_HOME/bin/java
fi
JAVACMD=/usr/bin/java
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

View file

@ -1,10 +1,6 @@
package land.chipmunk.chipmunkmod;
import com.google.gson.GsonBuilder;
import land.chipmunk.chipmunkmod.memory.ModuleMemory;
import land.chipmunk.chipmunkmod.util.Keybinds;
import land.chipmunk.chipmunkmod.util.SharedVariables;
import land.chipmunk.chipmunkmod.util.TickRunnableHandler;
import land.chipmunk.chipmunkmod.modules.KaboomCheck;
import land.chipmunk.chipmunkmod.modules.Players;
import land.chipmunk.chipmunkmod.modules.SelfCare;
@ -21,58 +17,39 @@ import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.math.BlockPos;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import java.nio.charset.Charset;
public class ChipmunkMod implements ModInitializer {
// This logger is used to write text to the console and the log file.
// It is considered best practice to use your mod id as the logger's name.
// That way, it's clear which mod wrote info, warnings, and errors.
public static final Logger LOGGER = LoggerFactory.getLogger("chipmunkmod");
public static Configuration CONFIG = new Configuration();
public static final File CONFIG_DIR = new File("config");
private static final File CONFIG_FILE = new File(CONFIG_DIR, "chipmunkmod.json");
public static Configuration CONFIG;
private static File CONFIG_DIR = new File("config");
private static File CONFIG_FILE = new File(CONFIG_DIR, "chipmunkmod.json");
public static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
public static final ModuleMemory MEMORY = new ModuleMemory();
@Override
public void onInitialize () {
// This code runs as soon as Minecraft is in a mod-load-ready state.
// However, some things (like resources) may still be uninitialized.
// Proceed with mild caution.
try {
CONFIG = loadConfig();
} catch (IOException exception) {
throw new RuntimeException("Could not load the config", exception);
}
Keybinds.registerOpenGui();
TickRunnableHandler.registerTickEndRunnables();
if(CONFIG.defaultUsername == null) CONFIG.defaultUsername = MinecraftClient.getInstance().getSession().getUsername(); // testclient gui is not loaded yet so getUsername will not retunr the fake
Players.INSTANCE.init();
KaboomCheck.INSTANCE.init();
SelfCare.INSTANCE.init();
//save on quit owo
ClientLifecycleEvents.CLIENT_STOPPING.register(client -> {
ModuleMemory.save();
try {
saveConfig();
} catch (IOException e) {
LOGGER.error("Failed to save config. Printing stacktrace.");
e.printStackTrace();
return;
}
LOGGER.info("Saved config!");
});
LOGGER.info("Loaded ChipmunkMod (name3's fork)");
LOGGER.info("Loaded ChipmunkMod (chayapak's fork)");
}
public static Configuration loadConfig () throws IOException {
@ -80,25 +57,28 @@ public class ChipmunkMod implements ModInitializer {
final Gson gson = new GsonBuilder()
.registerTypeAdapter(BlockPos.class, new BlockPosTypeAdapter())
.serializeNulls()
.create();
final File file = CONFIG_FILE;
if (!file.exists()) {
saveConfig();
InputStream is = ChipmunkMod.class.getClassLoader().getResourceAsStream("default_config.json");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
final StringBuilder sb = new StringBuilder();
while (reader.ready()) sb.append((char) reader.read());
final String defaultConfig = sb.toString();
// Write the default config
BufferedWriter configWriter = new BufferedWriter(new FileWriter(file));
configWriter.write(defaultConfig);
configWriter.close();
return gson.fromJson(defaultConfig, Configuration.class);
}
InputStream is = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF8")));
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
return gson.fromJson(reader, Configuration.class);
}
public static void saveConfig() throws IOException {
Gson otherGson = new GsonBuilder().serializeNulls().setLenient().setPrettyPrinting().create();
String defaultConfig = otherGson.toJson(CONFIG);
BufferedWriter configWriter = new BufferedWriter(new FileWriter(CONFIG_FILE, Charset.forName("UTF8")));
configWriter.write(defaultConfig);
configWriter.close();
}
}

View file

@ -1,24 +1,17 @@
package land.chipmunk.chipmunkmod;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import land.chipmunk.chipmunkmod.data.BlockArea;
import net.minecraft.util.math.BlockPos;
import java.util.HashMap;
public class Configuration {
public CommandManager commands = new CommandManager();
public CommandCore core = new CommandCore();
public Bots bots = new Bots();
public CustomChat customChat = new CustomChat();
public AntiSpam antiSpam = new AntiSpam();
public boolean fullbright = true; // unused, but it is here for old configs
public String autoSkinUsername = "off";
public String testbotWebhook = null;
public String defaultUsername = null;
public Memory memory = new Memory();
public static class CommandManager {
public String prefix = ".";
@ -34,10 +27,25 @@ public class Configuration {
public BotInfo ubot = new BotInfo("\"", null);
public BotInfo ubotdev = new BotInfo("d\"", null);
public BotInfo chipmunk = new BotInfo("'", null);
public ChomeNSBotInfo chomens = new ChomeNSBotInfo("*", null, null, null);
public BotInfo kittycorp = new BotInfo("^", null);
public TestBotInfo testbot = new TestBotInfo("-", null);
}
public static class ChomeNSBotInfo {
public String prefix;
public String key;
public String authKey;
public String formatKey;
public ChomeNSBotInfo (String prefix, String key, String authKey, String formatKey) {
this.prefix = prefix;
this.key = key;
this.authKey = authKey;
this.formatKey = formatKey;
}
}
public static class TestBotInfo {
public String prefix;
public String webhookUrl;
@ -59,30 +67,6 @@ public class Configuration {
}
public static class CustomChat {
public JsonObject format = new Gson().fromJson("""
{
"translate": "chat.type.text",
"with": [
{
"selector": "USERNAME"
},
{
"text": "MESSAGE"
}
]
}
""", JsonObject.class);
}
public static class AntiSpam {
public int matchingMessagesToBeSpam = 20;
public int messageTimeInTicks = 100;
public int minimumLevenshteinDistanceToBeSpam = 20;
}
public static class Memory {
public HashMap<String, Boolean> categories = new HashMap<>();
public HashMap<String, Boolean> modules = new HashMap<>();
public HashMap<String, String> options = new HashMap<>(); // will convert all values to their type according to the method specified in the option type thing
public JsonObject format;
}
}

View file

@ -5,7 +5,6 @@ import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.command.CommandException;
import net.minecraft.text.ClickEvent;
import net.minecraft.text.Text;
import net.minecraft.text.Texts;
@ -38,9 +37,7 @@ public class CommandManager {
SayCommand.register(this.dispatcher);
AutoSkinCommand.register(this.dispatcher);
ReloadConfigCommand.register(this.dispatcher);
// LoopCrouchCommand.register(this.dispatcher); // ^???????????????????
DebugCommand.register(this.dispatcher);
ClearAntiChatSpamQueueCommand.register(this.dispatcher);
SelfCareCommand.register(this.dispatcher);
KickCommand.register(this.dispatcher);
}
@ -55,8 +52,6 @@ public class CommandManager {
commandSource.sendError(Texts.toText(e.getRawMessage()));
final Text context = getContext(e);
if (context != null) commandSource.sendError(context);
} catch (CommandException e) {
commandSource.sendError(e.getTextMessage());
} catch (Exception e) {
commandSource.sendError(Text.of(e.getMessage()));
}

View file

@ -1,30 +0,0 @@
package land.chipmunk.chipmunkmod.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import land.chipmunk.chipmunkmod.util.Chat;
import land.chipmunk.chipmunkmod.util.Executor;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import java.util.List;
import java.util.concurrent.Executors;
import static land.chipmunk.chipmunkmod.command.CommandManager.literal;
public class ClearAntiChatSpamQueueCommand {
public static void register (CommandDispatcher<FabricClientCommandSource> dispatcher) {
final ClearAntiChatSpamQueueCommand instance = new ClearAntiChatSpamQueueCommand();
dispatcher.register(
literal("clearantichatspamqueue")
.executes(instance::run)
);
}
public int run(CommandContext<FabricClientCommandSource> context) throws CommandSyntaxException {
List<Runnable> runnables = Executor.antiChatSpamService.shutdownNow();
Executor.antiChatSpamService = Executors.newFixedThreadPool(1);
Chat.sendGreen("Stopped " + runnables.size() + " chat messages from getting recieved!");
return 1;
}
}

View file

@ -1,5 +1,6 @@
package land.chipmunk.chipmunkmod.commands;
import com.google.common.base.Suppliers;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.context.CommandContext;
@ -10,6 +11,8 @@ import static land.chipmunk.chipmunkmod.command.CommandManager.literal;
import static land.chipmunk.chipmunkmod.command.CommandManager.argument;
import static com.mojang.brigadier.arguments.StringArgumentType.greedyString;
import static com.mojang.brigadier.arguments.StringArgumentType.getString;
import land.chipmunk.chipmunkmod.util.TextUtilities;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.minecraft.text.Text;
import net.minecraft.nbt.NbtCompound;
@ -64,8 +67,9 @@ public class CoreCommand {
future.thenApply(tag -> {
try {
final String output = tag.getString("LastOutput");
if (output != null) source.sendFeedback(Text.Serializer.fromJson(output));
} catch (Exception ignored) {
if (output != null) source.sendFeedback(TextUtilities.fromJson(output));
} catch (Exception e) {
e.printStackTrace();
}
return tag;

View file

@ -1,65 +0,0 @@
package land.chipmunk.chipmunkmod.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import land.chipmunk.chipmunkmod.util.Debug;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import java.util.ArrayList;
import static land.chipmunk.chipmunkmod.command.CommandManager.literal;
import static land.chipmunk.chipmunkmod.command.CommandManager.argument;
import static com.mojang.brigadier.arguments.StringArgumentType.greedyString;
import static com.mojang.brigadier.arguments.StringArgumentType.string;
public class DebugCommand {
public static SuggestionProvider<FabricClientCommandSource> knownSuggestions = (context, builder) -> {
Debug.known.stream()
.filter(option -> option.startsWith(builder.getRemaining().toLowerCase()))
.forEach(builder::suggest);
return builder.buildFuture();
};
public static SuggestionProvider<FabricClientCommandSource> selectedSuggestions = (context, builder) -> {
Debug.selected.stream()
.filter(option -> option.startsWith(builder.getRemaining().toLowerCase()))
.forEach(builder::suggest);
return builder.buildFuture();
};
public static void register(CommandDispatcher<FabricClientCommandSource> dispatcher) {
dispatcher.register(
literal("debug")
.then(literal("add")
.then(argument("caller", string())
.suggests(knownSuggestions)
.executes(DebugCommand::add)))
.then(literal("remove")
.then(argument("caller", string())
.suggests(selectedSuggestions)
.executes(DebugCommand::remove)))
.then(literal("clear")
.executes(DebugCommand::clear))
);
}
public static int add(CommandContext<FabricClientCommandSource> context) {
String caller = context.getArgument("caller", String.class);
Debug.selected.add(caller);
context.getSource().sendFeedback(Text.literal("Added ").append(Text.literal(caller).formatted(Formatting.YELLOW)).append(Text.literal(" to the debug list!")));
return 0;
}
public static int remove(CommandContext<FabricClientCommandSource> context) {
String caller = context.getArgument("caller", String.class);
Debug.selected.remove(caller);
context.getSource().sendFeedback(Text.literal("Removed ").append(Text.literal(caller).formatted(Formatting.YELLOW)).append(Text.literal(" from the debug list!")));
return 0;
}
public static int clear(CommandContext<FabricClientCommandSource> context) {
Debug.selected = new ArrayList<>();
context.getSource().sendFeedback(Text.literal("Cleared the debug list!"));
return 0;
}
}

View file

@ -3,7 +3,6 @@ package land.chipmunk.chipmunkmod.commands;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.context.CommandContext;
import land.chipmunk.chipmunkmod.util.Eval;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.minecraft.client.MinecraftClient;
import net.minecraft.text.Text;
@ -22,22 +21,14 @@ public class EvalCommand {
public static void register (CommandDispatcher<FabricClientCommandSource> dispatcher) {
dispatcher.register(
literal("eval")
.then(literal("java")
.then(
argument("code", greedyString())
.executes(EvalCommand::evalJava)
)
)
.then(literal("lua")
.then(
argument("code", greedyString())
.executes(EvalCommand::evalLua)
)
.then(
argument("code", greedyString())
.executes(EvalCommand::eval)
)
);
}
public static int evalLua(CommandContext<FabricClientCommandSource> context) {
public static int eval (CommandContext<FabricClientCommandSource> context) {
final String code = getString(context, "code");
try {
@ -54,13 +45,6 @@ public class EvalCommand {
context.getSource().sendError(Text.literal(e.toString()));
}
return Command.SINGLE_SUCCESS;
}
public static int evalJava(CommandContext<FabricClientCommandSource> context) {
final String code = getString(context, "code");
Eval.shell(code);
return Command.SINGLE_SUCCESS;
}
}

View file

@ -8,6 +8,7 @@ import land.chipmunk.chipmunkmod.command.CommandManager;
import land.chipmunk.chipmunkmod.modules.SongPlayer;
import land.chipmunk.chipmunkmod.song.Song;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.JoinConfiguration;
import net.kyori.adventure.text.event.ClickEvent;
@ -219,7 +220,7 @@ public class MusicCommand {
mergedList.addAll(files);
final Component component = Component.translatable("Songs - %s", Component.join(JoinConfiguration.separator(Component.space()), mergedList)).color(NamedTextColor.GREEN);
MinecraftClient.getInstance().player.sendMessage(component);
((Audience) MinecraftClient.getInstance().player).sendMessage(component);
return 1;
}

View file

@ -9,8 +9,8 @@ import static land.chipmunk.chipmunkmod.command.CommandManager.literal;
import static land.chipmunk.chipmunkmod.command.CommandManager.argument;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.ConnectScreen;
import net.minecraft.client.gui.screen.TitleScreen;
import net.minecraft.client.gui.screen.multiplayer.ConnectScreen;
import net.minecraft.client.network.ServerInfo;
import net.minecraft.client.network.ServerAddress;
import net.minecraft.client.session.Session;
@ -61,7 +61,7 @@ public class UsernameCommand {
final ServerInfo info = client.getCurrentServerEntry();
client.world.disconnect();
client.disconnect();
ConnectScreen.connect(new TitleScreen(), client, ServerAddress.parse(info.address), info, false);
ConnectScreen.connect(new TitleScreen(), client, ServerAddress.parse(info.address), info, false, null);
return Command.SINGLE_SUCCESS;
}

View file

@ -19,6 +19,11 @@ public class ValidateCommand {
.then(literal("ubotdev").then(argument("command", greedyString()).executes(c -> ubotdev(getString(c, "command")))))
.then(literal("sbot").then(argument("command", greedyString()).executes(c -> sbot(getString(c, "command")))))
// .then(literal("chipmunk").then(argument("command", greedyString()).executes(c -> chipmunk(getString(c, "command")))))
.then(literal("chomens").then(argument("command", greedyString()).executes(c -> {
c.getSource().sendFeedback(Text.literal("Warning: Manual ChomeNS Bot validation is deprecated"));
return chomens(getString(c, "command"));
})))
.then(literal("kittycorp").then(argument("command", greedyString()).executes(c -> kittycorp(getString(c, "command")))))
);
}

View file

@ -0,0 +1,24 @@
package land.chipmunk.chipmunkmod.data;
import java.util.ArrayList;
import java.util.List;
public class ChomeNSBotCommand {
public final String name;
public final TrustLevel trustLevel;
public final List<String> aliases = new ArrayList<>();
public ChomeNSBotCommand (
String name,
TrustLevel trustLevel
) {
this.name = name;
this.trustLevel = trustLevel;
}
public enum TrustLevel {
PUBLIC,
TRUSTED,
OWNER
}
}

View file

@ -1,399 +0,0 @@
package land.chipmunk.chipmunkmod.memory;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.Configuration;
import land.chipmunk.chipmunkmod.testclient.gui.Gui;
import land.chipmunk.chipmunkmod.testclient.gui.components.Category;
import land.chipmunk.chipmunkmod.testclient.gui.components.Module;
import land.chipmunk.chipmunkmod.testclient.gui.components.Option;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import static land.chipmunk.chipmunkmod.ChipmunkMod.LOGGER;
// i have realised this can also be used to save profiles
// like it would be so simple to implement that feature
// not 1.1.0 tho it's taking too long
// whyt he fuck is this here lmao i have a working config jsut use that ??1'11'!?
public class ModuleMemory {
private static final File MEMORY_FILE = new File(ChipmunkMod.CONFIG_DIR, "chipmunkmodmemory.data");
public ArrayList<Category> categories = new ArrayList<>();
public void loadButOld() throws IOException {
if(!MEMORY_FILE.exists()) {
saveDefaults();
return;
}
// get the default values for everything and port it all to the local variables
for (land.chipmunk.chipmunkmod.testclient.gui.components.Category category : Gui.categoryList) {
Category localCategory = new Category(category.getMessage().getString(), false);
for (land.chipmunk.chipmunkmod.testclient.gui.components.Module module : category.moduleList) {
Module localModule = new Module(module.getMessage().getString(), module.isEnabled);
for (land.chipmunk.chipmunkmod.testclient.gui.components.Option<?> option : module.optionList) {
localModule.options.add(option.toMemoryOption());
}
localCategory.modules.add(localModule);
}
categories.add(localCategory);
}
FileReader reader = null;
try{
reader = new FileReader(MEMORY_FILE);
} catch(FileNotFoundException ignored) {} // this should never happen
// all the constant keywords for easy switchery
final String startKeyword = "start";
final String endKeyword = "end";
final String categoryKeyword = "category";
final String moduleKeyword = "module";
final String optionKeyword = "option";
final String commentKeyword = "comment";
// declare all variables needed
boolean hasStarted = false;
boolean hasEnded = false;
int charCode;
char character;
boolean isReading = false;
StringBuilder buffer = new StringBuilder();
int reading = 0; // 0=keyword, 1=category, 2=module, 3=option, 4=comment
int argument = 0;
String firstArgument = null;
String secondArgument = null;
String currentCategory = null;
String currentModule = null;
// do the magic reading
assert reader != null;
while(reader.ready() && !hasEnded) {
charCode = reader.read(); character = (char) charCode;
LOGGER.info("i read ac haracter woo "+character);
LOGGER.info("buffer is "+buffer.toString());
switch(character) {
case '\n' -> {} // nothing else will get executed (i think)
case ';' -> {
if(argument==2) {
LOGGER.info("arg is 2");
secondArgument = buffer.toString();
switch (reading) {
case 1 -> { // category
LOGGER.info("doing magic category thing owo AAAAAAAAAAAAAAAAAAAAAAAAAAAA");
// first argument is the name
boolean extended = Boolean.parseBoolean(secondArgument);// second argument is if it's extended
for (Category category : categories) {
LOGGER.info("comparing category "+category.name+" with argument "+firstArgument);
if(!category.name.equals(firstArgument)) continue;
LOGGER.info("found category "+category.name);
category.extended = extended;
break;
}
currentCategory = firstArgument;
}
case 2 -> { // module
// first argument is the name
if(currentCategory == null) {
LOGGER.warn(String.format("Found module %s before a category was declared! ignoring", firstArgument));
continue;
}
boolean enabled = Boolean.parseBoolean(secondArgument); // second argument is if it's enabled
for(Category category : categories) {
if(!category.name.equals(currentCategory)) continue;
for (Module module : category.modules) {
if(!module.name.equals(firstArgument)) continue;
module.enabled = enabled;
break;
}
break;
}
currentModule = firstArgument;
}
case 3 -> { // option
if(currentModule == null) {
LOGGER.warn(String.format("Found option %s before a module was declared! ignoring", firstArgument));
continue;
}
if(currentCategory == null) {
LOGGER.warn(String.format("Found option %s before a category was declared! ignoring", firstArgument));
continue;
}
for(Category category : categories) {
if(!category.name.equals(currentCategory)) continue;
for (Module module : category.modules) {
if(!module.name.equals(firstArgument)) continue;
for(Option<?> option : module.options) {
if(!option.name.equals(firstArgument)) continue;
setOptionValue(option, secondArgument);
break;
}
break;
}
break;
}
}
}
}
if(reading==0) switch (buffer.toString()) {
case startKeyword -> {
if(hasStarted) LOGGER.warn("Found multiple ;start statements, only accepting the first one.");
hasStarted = true;
LOGGER.info("found start astyemtnttnnnt owo");
}
case endKeyword -> hasEnded = true;
}
buffer = new StringBuilder();
isReading = true;
reading = 0;
argument = 0;
}
case ':' -> {
argument++;
switch (reading) {
case 0 -> {
switch (buffer.toString()) {
case categoryKeyword -> reading = 1;
case moduleKeyword -> reading = 2;
case optionKeyword -> reading = 3;
case commentKeyword -> reading = 4;
default -> LOGGER.warn("Unknown argumentful keyword '" + buffer + "', ignoring");
}
}
case 4 -> {} // comment
default -> { // category, module and option all have 2 args so I can treat them equally
if(argument==2) firstArgument = buffer.toString();
argument++;
}
}
buffer = new StringBuilder();
}
default -> {
if(!isReading) continue;
buffer.append(character);
}
}
}
if(!hasStarted) {
LOGGER.warn("Memory file exists but has no ;start statement! Overriding file...");
saveDefaults();
}
if(!hasEnded) {
LOGGER.warn("Memory file exists but has no ;end statement! Overriding file...");
saveDefaults();
}
}
public void apply() {
for (Category category : categories) {
// find matching category and set extended
// then loop through every module and do the same thing
// then loop through every option and do the same thing
// get the matching category
land.chipmunk.chipmunkmod.testclient.gui.components.Category realCategory = null;
for (land.chipmunk.chipmunkmod.testclient.gui.components.Category categoryInGui : Gui.categoryList) {
if(category.name.equals(categoryInGui.getMessage().getString())) {
// it's the right category
realCategory = categoryInGui;
break;
}
}
if(realCategory == null) {
LOGGER.warn(String.format("Category '%s' somehow not found in categoryInGui?? report to dev on discord @gboardclipboard because this is not supposed to be possible :DD", category.name));
continue;
}
LOGGER.info(String.format("Restoring category '%s' extended: %s", category.name, category.extended));
realCategory.isExtended = category.extended;
for(Module module : category.modules) {
land.chipmunk.chipmunkmod.testclient.gui.components.Module realModule = null;
for(land.chipmunk.chipmunkmod.testclient.gui.components.Module moduleInRealCategory : realCategory.moduleList) {
if(module.name.equals(moduleInRealCategory.getMessage().getString())) {
realModule = moduleInRealCategory;
break;
}
}
if(realModule == null) {
LOGGER.warn(String.format("Module '%s' somehow not found in category '%s'?? report to dev on discord @gboardclipboard because this is not supposed to be possible :DD", module.name, category.name));
continue;
}
LOGGER.info(String.format("Restoring module '%s' enabled: %s", module.name, module.enabled));
realModule.isEnabled = module.enabled;
for(Option<?> option : module.options) {
land.chipmunk.chipmunkmod.testclient.gui.components.Option<?> realOption = null;
for(land.chipmunk.chipmunkmod.testclient.gui.components.Option<?> optionInRealModule : realModule.optionList) {
if(option.name.equals(optionInRealModule.name)) {
realOption = optionInRealModule;
break;
}
}
if(realOption == null) {
LOGGER.warn(String.format("Option '%s' somehow not found in module '%s' in category '%s'?? report to dev on discord @gboardclipboard because this is not supposed to be possible :DD", option.name, module.name, category.name));
continue;
}
LOGGER.info(String.format("Restoring option '%s' value: %s", option.name, option.value));
setRealOptionValue(realOption, option);
}
}
}
}
public void saveDefaults() {
}
public <T> void setRealOptionValue(land.chipmunk.chipmunkmod.testclient.gui.components.Option<T> real, Option<?> fake) {
real.optionValue = (T) fake.value; // shut the fuck up intellij this cast is fine
}
public <T> void setOptionValue(Option<T> option, String value) {
if(option.getType() == String.class) {
option.value = (T) value; // ignore warning it's (String) string
} else if (option.getType() == Integer.class) {
Integer newValue = null;
try {
newValue = Integer.valueOf(value);
} catch (NumberFormatException e) {
LOGGER.warn(String.format("Option %s expects an integer, however the value '%s' cannot be parsed as one.", option.name, value));
return;
}
option.value = (T) newValue;
} else if (option.getType() == Double.class) {
Double newValue = null;
try {
newValue = Double.valueOf(value);
} catch (NumberFormatException e) {
LOGGER.warn(String.format("Option %s expects a double, however the value '%s' cannot be parsed as one.", option.name, value));
return;
}
option.value = (T) newValue;
} else {
throw new UnknownOptionTypeException(option.getType());
// no need to catch
// because pro runtime exception
}
}
public static class Category {
public final String name;
public boolean extended;
public ArrayList<Module> modules = new ArrayList<>();
public Category(String name, boolean extended) {
this.name = name;
this.extended = extended;
}
}
public static class Module {
public final String name;
public boolean enabled;
public ArrayList<Option<?>> options = new ArrayList<>();
public Module(String name, boolean enabled) {
this.name = name;
this.enabled = enabled;
}
}
public static class Option<T extends Object> {
public final String name;
public T value;
public Option(String name, T value) {
this.name = name;
this.value = value;
}
public Class<T> getType() {return (Class<T>) value.getClass();} // ignore warning cause intellij has the stupid
}
public static void load() {
for (Map.Entry<String, Boolean> categoryInMemory : ChipmunkMod.CONFIG.memory.categories.entrySet()) {
for (land.chipmunk.chipmunkmod.testclient.gui.components.Category categoryInGui : Gui.categoryList) {
if(categoryInMemory.getKey().equals(categoryInGui.getMessage().getString())) {
categoryInGui.isExtended = categoryInMemory.getValue();
}
}
}
for (Map.Entry<String, Boolean> moduleInMemory : ChipmunkMod.CONFIG.memory.modules.entrySet()) {
String[] split = moduleInMemory.getKey().split("\\.");
String category = split[0];
String module = split[1];
for (land.chipmunk.chipmunkmod.testclient.gui.components.Category categoryInGui : Gui.categoryList) {
if(!categoryInGui.getMessage().getString().equals(category)) continue;
for (land.chipmunk.chipmunkmod.testclient.gui.components.Module moduleInGui : categoryInGui.moduleList) {
if(module.equals(moduleInGui.getMessage().getString())) {
moduleInGui.isEnabled = moduleInMemory.getValue();
}
}
}
}
for (Map.Entry<String, Boolean> moduleInMemory : ChipmunkMod.CONFIG.memory.modules.entrySet()) {
String[] split = moduleInMemory.getKey().split("\\.");
String category = split[0];
String module = split[1];
for (land.chipmunk.chipmunkmod.testclient.gui.components.Category categoryInGui : Gui.categoryList) {
if(!categoryInGui.getMessage().getString().equals(category)) continue;
for (land.chipmunk.chipmunkmod.testclient.gui.components.Module moduleInGui : categoryInGui.moduleList) {
if(module.equals(moduleInGui.getMessage().getString())) {
moduleInGui.isEnabled = moduleInMemory.getValue();
}
}
}
}
for (Map.Entry<String, String> optionInMemory : ChipmunkMod.CONFIG.memory.options.entrySet()) {
String[] split = optionInMemory.getKey().split("\\.");
String category = split[0];
String module = split[1];
String option = split[2];
for (land.chipmunk.chipmunkmod.testclient.gui.components.Category categoryInGui : Gui.categoryList) {
if(!categoryInGui.getMessage().getString().equals(category)) continue;
for (land.chipmunk.chipmunkmod.testclient.gui.components.Module moduleInGui : categoryInGui.moduleList) {
if(!module.equals(moduleInGui.getMessage().getString())) continue;
for (land.chipmunk.chipmunkmod.testclient.gui.components.Option<?> optionInGui : moduleInGui.optionList) {
if(option.equals(optionInGui.name)) {
optionInGui.setValueFromString(optionInMemory.getValue());
}
}
}
}
}
LOGGER.info("Loaded module memory!");
}
public static void save() {
for (land.chipmunk.chipmunkmod.testclient.gui.components.Category categoryInGui : Gui.categoryList) {
String categoryKey = categoryInGui.getMessage().getString();
ChipmunkMod.CONFIG.memory.categories.put(categoryKey, categoryInGui.isExtended);
for (land.chipmunk.chipmunkmod.testclient.gui.components.Module moduleInGui : categoryInGui.moduleList) {
String moduleKey = categoryKey + "." + moduleInGui.getMessage().getString();
ChipmunkMod.CONFIG.memory.modules.put(moduleKey, moduleInGui.isEnabled);
for (land.chipmunk.chipmunkmod.testclient.gui.components.Option<?> optionInGui : moduleInGui.optionList) {
String key = moduleKey + "." + optionInGui.name;
ChipmunkMod.CONFIG.memory.options.put(key, optionInGui.getValueAsString());
}
}
}
}
}

View file

@ -1,7 +0,0 @@
package land.chipmunk.chipmunkmod.memory;
public class UnknownOptionTypeException extends RuntimeException { //runtime exception because i dont wanna catch this i just want it to crash me when something goes wrong
public UnknownOptionTypeException(Class<?> type) {
super(String.format("An option with type %s is not handled by ModuleMemory.", type.getTypeName()));
}
}

View file

@ -1,88 +0,0 @@
package land.chipmunk.chipmunkmod.mixin;
import land.chipmunk.chipmunkmod.listeners.Listener;
import land.chipmunk.chipmunkmod.listeners.ListenerManager;
import land.chipmunk.chipmunkmod.modules.RainbowName;
import land.chipmunk.chipmunkmod.testclient.modules.anti_annoyances.AntiChatSpamModule;
import land.chipmunk.chipmunkmod.util.Debug;
import land.chipmunk.chipmunkmod.util.Executor;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.hud.MessageIndicator;
import net.minecraft.network.message.MessageSignatureData;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableTextContent;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(net.minecraft.client.gui.hud.ChatHud.class)
public abstract class ChatHudMixin {
@Shadow protected abstract void addMessage(Text message, @Nullable MessageSignatureData signature, int ticks, @Nullable MessageIndicator indicator, boolean refresh);
@Shadow @Final private MinecraftClient client;
@Shadow protected abstract void logChatMessage(Text message, @Nullable MessageIndicator indicator);
@Inject(method = "addMessage(Lnet/minecraft/text/Text;Lnet/minecraft/network/message/MessageSignatureData;Lnet/minecraft/client/gui/hud/MessageIndicator;)V", at = @At("HEAD"), cancellable = true)
public void chipmunkmod$preventDoubleMessageLogging(Text message, MessageSignatureData signature, MessageIndicator indicator, CallbackInfo ci) {
// addMessage(message, signature, client.inGameHud.getTicks(), indicator, false);
if(false) ci.cancel();
}
@Inject(at = @At("HEAD"), method = "addMessage(Lnet/minecraft/text/Text;Lnet/minecraft/network/message/MessageSignatureData;ILnet/minecraft/client/gui/hud/MessageIndicator;Z)V", cancellable = true)
public void chipmunkmod$generalAddMessageMixin(Text message, MessageSignatureData signature, int ticks, MessageIndicator indicator, boolean refresh, CallbackInfo ci) {
// ChipmunkMod.LOGGER.info("gex");
if(AntiChatSpamModule.instance.isEnabled && message.equals(AntiChatSpamModule.latestPassedThroughMessage)) {
AntiChatSpamModule.latestPassedThroughMessage = Text.empty();
logChatMessage(message, indicator);
return;
}
// ChipmunkMod.LOGGER.info("gex2");
try {
if (RainbowName.INSTANCE.enabled) {
if (message.getString().contains("Your nickname is now ") || message.getString().contains("Nickname changed.")) {
ci.cancel();
return;
}
}
if (((TranslatableTextContent) message.getContent()).getKey().equals("advMode.setCommand.success")) {
ci.cancel();
return;
}
} catch (ClassCastException ignored) {}
for (Listener listener : ListenerManager.listeners) {
listener.chatMessageReceived(message);
}
// for (AntiChatSpamModule.BlockedPattern pattern : AntiChatSpamModule.instance.patterns) {
// if(pattern.pattern().matcher(message.getString()).matches()) ci.cancel();
// }
// ChipmunkMod.LOGGER.info("gex3");
if(AntiChatSpamModule.instance.isEnabled) {
Executor.antiChatSpamService.submit(() -> {
try {
Debug.debug("started a run or wahever", "AntiChatSpam.addMessage.future");
AntiChatSpamModule.ChatMessage cmessage = new AntiChatSpamModule.ChatMessage(message.getString());
Debug.debug("hidden: " + cmessage.hidden, "AntiChatSpam.addMessage.future");
if (cmessage.hidden) return;
AntiChatSpamModule.latestPassedThroughMessage = message;
Debug.debug("changed variable in module class", "AntiChatSpam.addMessage.future");
MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(message, signature, indicator);
Debug.debug("ended a run or wahever", "AntiChatSpam.addMessage.future");
} catch (Exception e) {
e.printStackTrace();
}
});
ci.cancel();
}
}
}

View file

@ -6,6 +6,7 @@ import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.command.CommandManager;
import land.chipmunk.chipmunkmod.modules.ChomeNSBotCommandSuggestions;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.widget.TextFieldWidget;
@ -54,7 +55,30 @@ public class ChatInputSuggestorMixin {
final ClientPlayerEntity player = MinecraftClient.getInstance().player;
if (cursor > commandManager.prefix.length() && text.startsWith(commandManager.prefix)) {
final String chomeNSPrefix = ChipmunkMod.CONFIG.bots.chomens.prefix;
if (!text.contains(" ") && text.startsWith(chomeNSPrefix) && player != null) {
final String textUpToCursor = text.substring(0, cursor);
final List<String> commands = ChomeNSBotCommandSuggestions.INSTANCE.commands
.stream()
.map((command) -> command.name)
.toList();
pendingSuggestions = CommandSource.suggestMatching(
commands,
new SuggestionsBuilder(
textUpToCursor,
getStartOfCurrentWord(textUpToCursor)
)
);
pendingSuggestions.thenRun(() -> {
if (!pendingSuggestions.isDone()) return;
show(true);
});
} else if (cursor > commandManager.prefix.length() && text.startsWith(commandManager.prefix)) {
final StringReader reader = new StringReader(text);
reader.setCursor(commandManager.prefix.length()); // Skip the prefix

View file

@ -2,23 +2,17 @@ package land.chipmunk.chipmunkmod.mixin;
import com.google.gson.JsonObject;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.data.ChomeNSBotCommand;
import land.chipmunk.chipmunkmod.modules.ChomeNSBotCommandSuggestions;
import land.chipmunk.chipmunkmod.util.BotValidationUtilities;
import land.chipmunk.chipmunkmod.util.Executor;
import land.chipmunk.chipmunkmod.util.Webhook;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.ChatInputSuggestor;
import net.minecraft.client.gui.screen.Screen;
import land.chipmunk.chipmunkmod.util.SharedVariables;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
@ -36,23 +30,74 @@ public class ChatScreenMixin extends Screen {
this.originalChatText = originalChatText;
}
@Inject(at = @At("HEAD"), method = "sendMessage", cancellable = true)
public void sendMessage(String chatText, boolean addToHistory, CallbackInfoReturnable<Boolean> cir) {
final MinecraftClient client = MinecraftClient.getInstance();
@Inject(method = "sendMessage", at = @At("HEAD"), cancellable = true)
private void sendMessage (String chatText, boolean addToHistory, CallbackInfo cir) {
final MinecraftClient client = MinecraftClient.getInstance();
if (addToHistory) {
client.inGameHud.getChatHud().addToMessageHistory(chatText);
}
if(ChipmunkMod.CONFIG.testbotWebhook != null && chatText.startsWith("-")) {
Executor.service.submit(() -> {
if (addToHistory) {
client.inGameHud.getChatHud().addToMessageHistory(chatText);
}
if (ChipmunkMod.CONFIG.bots.testbot.webhookUrl != null && chatText.startsWith(ChipmunkMod.CONFIG.bots.testbot.prefix)) {
ChipmunkMod.executorService.submit(() -> {
try {
Webhook.send(ChipmunkMod.CONFIG.testbotWebhook, ChipmunkMod.CONFIG.defaultUsername);
final URL url = new URL(ChipmunkMod.CONFIG.bots.testbot.webhookUrl);
final HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("User-Agent", "ChipmunkMod");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
final JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("username", "ChipmunkMod UwU");
jsonObject.addProperty("content", MinecraftClient.getInstance().getSession().getUsername());
final OutputStream stream = connection.getOutputStream();
stream.write(jsonObject.toString().getBytes());
stream.flush();
stream.close();
connection.getInputStream().close();
connection.disconnect();
} catch (IOException e) {
ChipmunkMod.LOGGER.error("fard webhook url !!!t");
e.printStackTrace();
}
});
} else if (chatText.startsWith(ChipmunkMod.CONFIG.bots.chomens.prefix)) {
final List<ChomeNSBotCommand> commands = ChomeNSBotCommandSuggestions.INSTANCE.commands;
final List<String> moreOrTrustedCommands = commands.stream()
.filter((command) -> command.trustLevel != ChomeNSBotCommand.TrustLevel.PUBLIC)
.map((command) -> command.name.toLowerCase())
.toList();
final List<String> aliases = new ArrayList<>();
for (ChomeNSBotCommand command : commands) {
if (command.trustLevel == ChomeNSBotCommand.TrustLevel.PUBLIC) continue;
aliases.addAll(command.aliases);
}
final String chatCommand = chatText.toLowerCase().split("\\s")[0];
final int prefixLength = ChipmunkMod.CONFIG.bots.chomens.prefix.length();
if (
moreOrTrustedCommands.contains(chatCommand) ||
aliases.contains(chatCommand.substring(prefixLength))
) {
try {
BotValidationUtilities.chomens(chatText.substring(prefixLength));
cir.cancel();
return;
} catch (Exception ignored) {}
}
}
if (client == null) return;
if (chatText.startsWith("/")) {
@ -61,8 +106,6 @@ public class ChatScreenMixin extends Screen {
client.player.networkHandler.sendChatMessage(chatText);
}
cir.setReturnValue(true);
cir.cancel();
}
}

View file

@ -4,8 +4,6 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.DecoderException;
import land.chipmunk.chipmunkmod.listeners.Listener;
import land.chipmunk.chipmunkmod.listeners.ListenerManager;
import land.chipmunk.chipmunkmod.testclient.modules.lag_prevention.AntiParticleKickModule;
import land.chipmunk.chipmunkmod.util.Chat;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.network.listener.PacketListener;
@ -39,7 +37,6 @@ public class ClientConnectionMixin {
@Inject(method = "exceptionCaught", at = @At("HEAD"), cancellable = true)
private void exceptionCaught (ChannelHandlerContext context, Throwable ex, CallbackInfo ci) {
Chat.sendGold("ChipmunkMod caught an exception in ClientConnection.");
ci.cancel();
ex.printStackTrace();
}
@ -54,10 +51,10 @@ public class ClientConnectionMixin {
// please don't skid this.,.
// mabe mabe mabe
// lol i had my own im just gonna cop ypaste that :D
if(packet instanceof ParticleS2CPacket) {
if(AntiParticleKickModule.instance.isEnabled && ((ParticleS2CPacket) packet).getCount()>1000) {
if(((ParticleS2CPacket) packet).getCount()>1000) Chat.sendGold("ChipmunkMod prevented a particle kick!");
if (packet instanceof ParticleS2CPacket t_packet) {
final double max = 1000;
if (t_packet.getCount() > max) {
ci.cancel();
}
} else if (packet instanceof PlaySoundS2CPacket t_packet) {
@ -79,7 +76,7 @@ public class ClientConnectionMixin {
if (world == null) return;
// huge mess
final SoundEvent newSound = SoundEvent.of(new Identifier(sound.getNamespace(), sound.getPath().substring(0, sound.getPath().length() - (".pitch." + stringPitch).length())));
final SoundEvent newSound = SoundEvent.of(Identifier.of(sound.getNamespace(), sound.getPath().substring(0, sound.getPath().length() - (".pitch." + stringPitch).length())));
client.executeSync(() -> world.playSound(client.player, t_packet.getX(), t_packet.getY(), t_packet.getZ(), newSound, t_packet.getCategory(), t_packet.getVolume(), pitch, t_packet.getSeed()));
@ -95,7 +92,7 @@ public class ClientConnectionMixin {
@Inject(at = @At("HEAD"), method = "send(Lnet/minecraft/network/packet/Packet;)V", cancellable = true)
private void sendPacket (Packet<?> packet, CallbackInfo ci) {
if (packet instanceof RequestCommandCompletionsC2SPacket t_packet) {
if (t_packet.getPartialCommand().length() > 2048) { // why was this comment here
if (t_packet.getPartialCommand().length() > 2048) {
ci.cancel();
return;
}

View file

@ -5,6 +5,8 @@ import land.chipmunk.chipmunkmod.command.CommandManager;
import land.chipmunk.chipmunkmod.listeners.Listener;
import land.chipmunk.chipmunkmod.listeners.ListenerManager;
import land.chipmunk.chipmunkmod.modules.*;
import net.kyori.adventure.platform.fabric.FabricAudiences;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.minecraft.client.MinecraftClient;
import net.minecraft.command.CommandRegistryAccess;
@ -19,6 +21,7 @@ import net.minecraft.network.packet.s2c.play.GameMessageS2CPacket;
import net.minecraft.network.packet.s2c.play.PlayerRemoveS2CPacket;
import net.minecraft.registry.DynamicRegistryManager;
import net.minecraft.resource.featuretoggle.FeatureSet;
import net.minecraft.text.PlainTextContent;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableTextContent;
import org.spongepowered.asm.mixin.Final;
@ -49,6 +52,8 @@ public class ClientPlayNetworkHandlerMixin {
CommandCore.INSTANCE.init();
SongPlayer.INSTANCE.coreReady();
RainbowName.INSTANCE.init();
ChomeNSBotCommandSuggestions.INSTANCE.init();
ChomeNSAuth.INSTANCE.init();
CustomChat.INSTANCE.init();
}
@ -77,9 +82,16 @@ public class ClientPlayNetworkHandlerMixin {
for (Listener listener : ListenerManager.listeners) {
listener.chatMessageReceived(message);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
final String suggestionId = message.getSiblings().getFirst().getString();
final String authId = ((PlainTextContent) message.getContent()).string();
if (suggestionId.equals(ChomeNSBotCommandSuggestions.ID) || authId.equals(ChomeNSAuth.INSTANCE.id)) {
ci.cancel();
}
} catch (Exception ignored) {}
} catch (Exception ignored) {}
}
@Inject(method = "sendChatMessage", at = @At("HEAD"), cancellable = true)

View file

@ -1,22 +0,0 @@
package land.chipmunk.chipmunkmod.mixin;
import net.minecraft.block.entity.DecoratedPotBlockEntity;
import net.minecraft.item.Item;
import net.minecraft.item.Items;
import net.minecraft.nbt.NbtElement;
import net.minecraft.nbt.NbtList;
import net.minecraft.util.Identifier;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
// https://github.com/LunaWasFlaggedAgain/Mojang-ResourceLocation-Challenge/blob/main/src/main/java/com/github/lunawasflaggedagain/mojangresourcelocationchallenge/mixin/DecoratedPotBlockEntitySherdsMixin.java
@Mixin(DecoratedPotBlockEntity.Sherds.class)
public class DecoratedPotBlockEntitySherdsMixin {
@Inject(method = "getSherd", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/Identifier;tryParse(Ljava/lang/String;)Lnet/minecraft/util/Identifier;"), locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true)
private static void getSherd(NbtList list, int index, CallbackInfoReturnable<Item> cir, NbtElement nbtElement) {
if (!Identifier.isValid(nbtElement.asString())) cir.setReturnValue(Items.BRICK);
}
}

View file

@ -1,11 +1,9 @@
package land.chipmunk.chipmunkmod.mixin;
import land.chipmunk.chipmunkmod.testclient.modules.lag_prevention.BlockGuardianParticlesModule;
import land.chipmunk.chipmunkmod.util.SharedVariables;
import net.minecraft.client.particle.ElderGuardianAppearanceParticle;
import net.minecraft.client.particle.Particle;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.particle.DefaultParticleType;
import net.minecraft.particle.SimpleParticleType;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
@ -13,10 +11,10 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(ElderGuardianAppearanceParticle.Factory.class)
public class ElderGuardianAppearanceParticleMixin {
@Inject(method = "createParticle(Lnet/minecraft/particle/DefaultParticleType;Lnet/minecraft/client/world/ClientWorld;DDDDDD)Lnet/minecraft/client/particle/Particle;", at = @At("HEAD"), cancellable = true)
private void testClient$limitGuardianParticles(DefaultParticleType defaultParticleType, ClientWorld clientWorld, double d, double e, double f, double g, double h, double i, CallbackInfoReturnable<Particle> cir) {
if(BlockGuardianParticlesModule.instance.isEnabled) cir.cancel();
if(SharedVariables.elderGuardianParticleTimer > 0) cir.cancel();
SharedVariables.elderGuardianParticleTimer = 200;
@Inject(method = "createParticle(Lnet/minecraft/particle/SimpleParticleType;Lnet/minecraft/client/world/ClientWorld;DDDDDD)Lnet/minecraft/client/particle/Particle;", at = @At("HEAD"))
private void createParticle (SimpleParticleType simpleParticleType, ClientWorld clientWorld, double d, double e, double f, double g, double h, double i, CallbackInfoReturnable<Particle> cir) {
if (cir.isCancelled() || !cir.isCancellable()) return;
cir.cancel();
}
}

View file

@ -1,28 +0,0 @@
package land.chipmunk.chipmunkmod.mixin;
import land.chipmunk.chipmunkmod.testclient.modules.lag_prevention.AntiTextObfuscationLagModule;
import net.minecraft.client.font.FontStorage;
import net.minecraft.client.font.Glyph;
import net.minecraft.client.font.GlyphRenderer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.time.Instant;
@Mixin(FontStorage.class)
public class FontStorageMixin {
@Shadow private GlyphRenderer blankGlyphRenderer;
@Inject(method = "getObfuscatedGlyphRenderer", at = @At("HEAD"), cancellable = true)
private void chipmunkmod$preventObfuscatedGlyphLag(Glyph glyph, CallbackInfoReturnable<GlyphRenderer> cir) {
if(!AntiTextObfuscationLagModule.instance.isEnabled) return;
if(AntiTextObfuscationLagModule.instance.exceededLimitThisTick || Instant.now().toEpochMilli() - AntiTextObfuscationLagModule.instance.renderTimeStart.toEpochMilli() > 18) {
AntiTextObfuscationLagModule.instance.exceededLimitThisTick = true;
cir.setReturnValue(blankGlyphRenderer);
}
// Debug.debug("Render time: "+(Instant.now().toEpochMilli() - AntiTextObfuscationLagModule.instance.renderTimeStart.toEpochMilli()), "AntiTextObfuscationLag.mixin");
}
}

View file

@ -1,53 +0,0 @@
package land.chipmunk.chipmunkmod.mixin;
import net.minecraft.client.input.Input;
import net.minecraft.client.input.KeyboardInput;
import net.minecraft.client.option.GameOptions;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(KeyboardInput.class)
public class KeyboardInputMixin extends Input {
@Final
@Mutable
@Shadow
private final GameOptions settings;
public KeyboardInputMixin (GameOptions settings) {
this.settings = settings;
}
@Inject(method = "tick", at = @At("TAIL"))
private void tick (boolean slowDown, float f, CallbackInfo ci) {
this.pressingForward = this.settings.forwardKey.isPressed();
this.pressingBack = this.settings.backKey.isPressed();
this.pressingLeft = this.settings.leftKey.isPressed();
this.pressingRight = this.settings.rightKey.isPressed();
this.movementForward = getMovementMultiplier(this.pressingForward, this.pressingBack);
this.movementSideways = getMovementMultiplier(this.pressingLeft, this.pressingRight);
this.jumping = this.settings.jumpKey.isPressed();
// wtf loopcrougchs gone??????????????
// this.sneaking = LoopCrouch.INSTANCE.enabled() ?
// !LoopCrouch.INSTANCE.sneaking() :
// this.settings.sneakKey.isPressed();
// LoopCrouch.INSTANCE.sneaking(!LoopCrouch.INSTANCE.sneaking());
if (slowDown) {
this.movementSideways *= f;
this.movementForward *= f;
}
}
private static float getMovementMultiplier(boolean positive, boolean negative) {
if (positive == negative) {
return 0.0f;
}
return positive ? 1.0f : -1.0f;
}
}

View file

@ -1,34 +0,0 @@
package land.chipmunk.chipmunkmod.mixin;
import net.minecraft.client.Keyboard;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import org.lwjgl.glfw.GLFW;
import org.objectweb.asm.Opcodes;
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.Redirect;
import org.spongepowered.asm.mixin.injection.Slice;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Keyboard.class)
public class KeyboardMixin {
// Don't @ me. It half-works
// LUNA WHAT THE FUCK IS THIS MIXIN AM I SUPPOSED TO UNDERSTAND THIS
@Redirect(method = "onKey(JIIII)V",
at = @At(value = "FIELD", target = "Lnet/minecraft/client/MinecraftClient;currentScreen:Lnet/minecraft/client/gui/screen/Screen;", opcode = Opcodes.GETFIELD),
slice = @Slice(
from = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screen/Screen;wrapScreenError(Ljava/lang/Runnable;Ljava/lang/String;Ljava/lang/String;)V"),
to = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/InputUtil;fromKeyCode(II)Lnet/minecraft/client/util/InputUtil$Key;")
)
)
private Screen currentScreen(MinecraftClient instance) {
// if (GuiMoveModule.instance.isEnabled) {
// return null;
// } else {
return instance.currentScreen;
// }
}
}

View file

@ -1,34 +0,0 @@
package land.chipmunk.chipmunkmod.mixin;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.util.SharedVariables;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.multiplayer.MultiplayerScreen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.text.Text;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(MultiplayerScreen.class)
public class MultiplayerScreenMixin extends Screen{
@Shadow private ButtonWidget buttonEdit;
protected MultiplayerScreenMixin(Text title) {
super(title);
}
@Inject(method="init", at = @At("TAIL"))
private void testclient$addUsernameField(CallbackInfo ci) {
TextFieldWidget usernameField = new TextFieldWidget(textRenderer, buttonEdit.getX()-130, buttonEdit.getY(), 120, 20, Text.literal("Username"));;
usernameField.setText(ChipmunkMod.CONFIG.defaultUsername);
usernameField.setChangedListener(text -> {
ChipmunkMod.CONFIG.defaultUsername = text;
});
usernameField.setMaxLength(16);
addDrawableChild(usernameField);
}
}

View file

@ -1,22 +0,0 @@
package land.chipmunk.chipmunkmod.mixin;
import net.minecraft.network.handler.PacketBundleHandler;
import net.minecraft.network.listener.PacketListener;
import net.minecraft.network.packet.BundlePacket;
import net.minecraft.network.packet.BundleSplitterPacket;
import net.minecraft.network.packet.Packet;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
@Mixin(PacketBundleHandler.class)
public interface PacketBundleHandlerMixin {
}

View file

@ -1,12 +0,0 @@
package land.chipmunk.chipmunkmod.mixin;
import net.minecraft.block.Block;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(Block.class)
public class PlayerEntityMixin {
//slippery world was here
//TODO: remove
}

View file

@ -1,22 +0,0 @@
package land.chipmunk.chipmunkmod.mixin;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.testclient.gui.Gui;
import land.chipmunk.chipmunkmod.util.SharedVariables;
import net.minecraft.client.session.Session;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(Session.class)
public abstract class SessionMixin {
@Shadow public abstract Session.AccountType getAccountType();
@Inject(method = "getUsername", at=@At("RETURN"), cancellable = true)
void testclient$overrideUsernameGetter(CallbackInfoReturnable<String> cir) {
// only overrides when gui has been initialized cause issues
if(Gui.gui != null) cir.setReturnValue(ChipmunkMod.CONFIG.defaultUsername);
}
}

View file

@ -1,16 +0,0 @@
package land.chipmunk.chipmunkmod.mixin;
import net.minecraft.SharedConstants;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(SharedConstants.class)
public class SharedConstantsMixin {
@Inject(method = "isValidChar", at = @At("HEAD"), cancellable = true)
private static void isValidChar (char chr, CallbackInfoReturnable<Boolean> cir) {
cir.setReturnValue(chr >= ' ' && chr != '\u007f');
cir.cancel();
}
}

View file

@ -19,4 +19,10 @@ public class StringHelperMixin {
cir.setReturnValue(text);
cir.cancel();
}
@Inject(method = "isValidChar", at = @At("HEAD"), cancellable = true)
private static void isValidChar (char chr, CallbackInfoReturnable<Boolean> cir) {
cir.setReturnValue(chr >= ' ' && chr != '\u007f');
cir.cancel();
}
}

View file

@ -14,12 +14,13 @@ import java.util.Optional;
@Mixin(Text.class)
public interface TextMixin {
@Inject(method = "visit(Lnet/minecraft/text/StringVisitable$Visitor;)Ljava/util/Optional;", at = @At(value = "INVOKE", target = "Lnet/minecraft/text/Text;visit(Lnet/minecraft/text/StringVisitable$Visitor;)Ljava/util/Optional;"), locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true)
private <T> void testclient$preventVisitMethodCrash(StringVisitable.Visitor<T> visitor, CallbackInfoReturnable<Optional<T>> cir, Optional optional, Iterator var3, Text text) {
if(text == null) cir.setReturnValue(Optional.empty());
@Inject(method = "visit(Lnet/minecraft/text/StringVisitable$StyledVisitor;Lnet/minecraft/text/Style;)Ljava/util/Optional;", at = @At(value = "INVOKE", target = "Lnet/minecraft/text/Text;visit(Lnet/minecraft/text/StringVisitable$StyledVisitor;Lnet/minecraft/text/Style;)Ljava/util/Optional;"), cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD)
private <T> void visit (StringVisitable.StyledVisitor<T> styledVisitor, Style style, CallbackInfoReturnable<Optional<T>> cir, Style style2, Optional optional, Iterator var5, Text text) {
if (text == null) cir.setReturnValue(Optional.empty());
}
@Inject(method = "visit(Lnet/minecraft/text/StringVisitable$StyledVisitor;Lnet/minecraft/text/Style;)Ljava/util/Optional;", at = @At(value = "INVOKE", target = "Lnet/minecraft/text/Text;visit(Lnet/minecraft/text/StringVisitable$StyledVisitor;Lnet/minecraft/text/Style;)Ljava/util/Optional;"), locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true)
private <T> void testclient$preventVisitMethodCrash2(StringVisitable.StyledVisitor<T> styledVisitor, Style style, CallbackInfoReturnable<Optional<T>> cir, Style style2, Optional optional, Iterator var5, Text text) {
if(text == null) cir.setReturnValue(Optional.empty());
@Inject(method = "visit(Lnet/minecraft/text/StringVisitable$Visitor;)Ljava/util/Optional;", at = @At(value = "INVOKE", target = "Lnet/minecraft/text/Text;visit(Lnet/minecraft/text/StringVisitable$Visitor;)Ljava/util/Optional;"), cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD)
private <T> void visit (StringVisitable.Visitor<T> visitor, CallbackInfoReturnable<Optional<T>> cir, Optional optional, Iterator var3, Text text) {
if (text == null) cir.setReturnValue(Optional.empty());
}
}

View file

@ -59,9 +59,4 @@ public class TextSerializerMixin {
cir.cancel();
}
@Inject(method = "deserialize(Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lnet/minecraft/text/MutableText;", at = @At("HEAD"), cancellable = true)
private void testclient$preventChatOverflowExploit(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext, CallbackInfoReturnable<MutableText> cir) {
Throwable throwable = new Throwable();
if(throwable.getStackTrace().length >= 700) cir.setReturnValue(Text.literal("TestClient prevented a text overflow exploit i think ("+throwable.getStackTrace().length+")").formatted(Formatting.GOLD));
}
}

View file

@ -1,32 +0,0 @@
package land.chipmunk.chipmunkmod.mixin;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.memory.ModuleMemory;
import land.chipmunk.chipmunkmod.testclient.gui.Gui;
import net.minecraft.client.gui.screen.SplashTextRenderer;
import net.minecraft.client.gui.screen.TitleScreen;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.io.IOException;
@Mixin(TitleScreen.class)
public class TitleScreenMixin {
@Inject(method = "init", at = @At("HEAD"))
void testclient$initializeGui(CallbackInfo ci) {
if(Gui.gui == null){
Gui.initAutoRefresher();
Gui.addComponents();
Gui.gui = new Gui();
ModuleMemory.load();
ChipmunkMod.LOGGER.info("Initialised gui!");
}
}
}

View file

@ -1,19 +0,0 @@
package land.chipmunk.chipmunkmod.mixin;
import land.chipmunk.chipmunkmod.testclient.modules.lag_prevention.AntiTextObfuscationLagModule;
import net.minecraft.client.render.WorldRenderer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.time.Instant;
@Mixin(WorldRenderer.class)
public class WorldRendererMixin {
@Inject(method = "render", at = @At("HEAD"))
private void chipmunkmod$saveRenderStartTime(CallbackInfo ci) {
AntiTextObfuscationLagModule.instance.renderTimeStart = Instant.now();
AntiTextObfuscationLagModule.instance.exceededLimitThisTick = false;
}
}

View file

@ -0,0 +1,80 @@
package land.chipmunk.chipmunkmod.modules;
import com.google.common.hash.Hashing;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.listeners.Listener;
import land.chipmunk.chipmunkmod.listeners.ListenerManager;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.minecraft.text.PlainTextContent;
import net.minecraft.text.Text;
import net.minecraft.text.TextContent;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class ChomeNSAuth extends Listener {
public static final ChomeNSAuth INSTANCE = new ChomeNSAuth();
public final String id = "chomens_bot_verify";
public ChomeNSAuth () {
ListenerManager.addListener(this);
}
public void init () {}
@Override
public void chatMessageReceived(Text text) {
final String authKey = ChipmunkMod.CONFIG.bots.chomens.authKey;
if (authKey == null) return;
final TextContent message = text.getContent();
if (!(message instanceof PlainTextContent)) return;
final String id = ((PlainTextContent) message).string();
if (!id.equals(this.id)) return;
final List<Text> children = text.getSiblings();
if (children.size() != 2) return;
if (!(children.getFirst().getContent() instanceof PlainTextContent)) return;
final String hash = ((PlainTextContent) children.getFirst().getContent()).string();
final long time = System.currentTimeMillis() / 10_000;
final String actual = Hashing.sha256()
// very pro hash input
.hashString(authKey + time, StandardCharsets.UTF_8)
.toString()
.substring(0, 8);
if (!hash.equals(actual)) return;
if (!(children.get(1).getContent() instanceof PlainTextContent)) return;
final String selector = ((PlainTextContent) children.get(1).getContent()).string();
final String toSendHash = Hashing.sha256()
// very pro hash input
.hashString(authKey + authKey + time + time, StandardCharsets.UTF_8)
.toString()
.substring(0, 8);
final Component toSend = Component.text(id)
.append(Component.text(toSendHash));
final String toSendString = GsonComponentSerializer.gson().serialize(toSend);
System.out.println("Sending " + toSendString + " to " + selector);
CommandCore.INSTANCE.run("tellraw " + selector + " " + toSendString);
CustomChat.INSTANCE.resetTotal();
}
}

View file

@ -0,0 +1,90 @@
package land.chipmunk.chipmunkmod.modules;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.data.ChomeNSBotCommand;
import land.chipmunk.chipmunkmod.listeners.Listener;
import land.chipmunk.chipmunkmod.listeners.ListenerManager;
import land.chipmunk.chipmunkmod.util.UUIDUtilities;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.text.PlainTextContent;
import net.minecraft.text.Text;
import java.util.ArrayList;
import java.util.List;
public class ChomeNSBotCommandSuggestions extends Listener {
public static final String ID = "chomens_bot_request_command_suggestion";
public static ChomeNSBotCommandSuggestions INSTANCE = new ChomeNSBotCommandSuggestions(MinecraftClient.getInstance());
private final MinecraftClient client;
public List<ChomeNSBotCommand> commands = new ArrayList<>();
public ChomeNSBotCommandSuggestions (MinecraftClient client) {
this.client = client;
ListenerManager.addListener(this);
}
public void init () {}
@Override
public void coreMoved () { forceRequest(); }
public void forceRequest () {
final ClientPlayerEntity player = client.player;
if (player == null) return;
final String selector = UUIDUtilities.selector(player.getUuid());
final Component component = Component
.text(ID)
.append(Component.text(selector));
final String serialized = GsonComponentSerializer.gson().serialize(component);
CommandCore.INSTANCE.run("tellraw @a[tag=chomens_bot] " + serialized);
}
@Override
public void chatMessageReceived(Text message) {
try {
final List<Text> children = message.getSiblings();
if (children.isEmpty()) return;
final Text textComponent = children.getFirst();
if (!textComponent.getString().equals(ID)) return;
commands = children.subList(1, children.size())
.stream()
.map(
(eachComponent) -> {
final ChomeNSBotCommand command = new ChomeNSBotCommand(
ChipmunkMod.CONFIG.bots.chomens.prefix + ((PlainTextContent) eachComponent.getContent()).string(),
ChomeNSBotCommand.TrustLevel.valueOf(eachComponent.getSiblings().getFirst().getString())
);
if (!Boolean.parseBoolean(eachComponent.getSiblings().get(1).getString())) return command;
final List<Text> subList = eachComponent.getSiblings().subList(2, eachComponent.getSiblings().size());
for (Text aliasComponent : subList) {
final String alias = aliasComponent.getString();
command.aliases.add(alias);
}
return command;
}
)
.toList();
} catch (Exception ignored) {}
}
}

View file

@ -147,9 +147,9 @@ public class CommandCore {
noPos.start.getZ() + origin.getZ()
),
new BlockPos(
noPos.start.getX() + origin.getX() + 15,
(int) MathUtilities.clamp(noPos.start.getY(), dimension.minY(), dimension.height()),
noPos.start.getZ() + origin.getZ() + 15
noPos.end.getX() + origin.getX(),
(int) MathUtilities.clamp(noPos.end.getY(), dimension.minY(), dimension.height()),
noPos.end.getZ() + origin.getZ()
)
);

View file

@ -5,6 +5,7 @@ import com.google.gson.JsonElement;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
@ -100,6 +101,15 @@ public class CustomChat {
final Component deserialized = serializer.deserialize(message);
final String messageWithColor = GsonComponentSerializer.gson().serialize(deserialized).replace("MESSAGE", randomized);
final String key = ChipmunkMod.CONFIG.bots.chomens.formatKey;
final String hash = key != null ?
Hashing.sha256()
.hashString(key + total, StandardCharsets.UTF_8)
.toString()
.substring(0, 8) :
"";
total++;
try {
@ -115,6 +125,7 @@ public class CustomChat {
// .replace("\"PREFIX\"", prefix)
// .replace("\"DISPLAYNAME\"", displayName)
.replace("USERNAME", username)
.replace("HASH", hash)
.replace("{\"text\":\"MESSAGE\"}", messageWithColor)
.replace("\"extra\":[\"MESSAGE\"],\"color\":", "\"extra\":[" + messageWithColor + "],\"color\":")
.replace("MESSAGE", sanitizedMessage.replaceAll("&.", ""))
@ -123,7 +134,7 @@ public class CustomChat {
CommandCore.INSTANCE.run((KaboomCheck.INSTANCE.isKaboom ? "minecraft:tellraw @a " : "tellraw @a ") + sanitizedFormat);
} catch (Exception e) {
if (client.player == null) return;
client.player.sendMessage(Component.text(e.toString()).color(NamedTextColor.RED));
((Audience) client.player).sendMessage(Component.text(e.toString()).color(NamedTextColor.RED));
}
}
}

View file

@ -66,7 +66,7 @@ public class KaboomCheck extends Listener {
}
}
return packet;
return true;
});
}

View file

@ -107,7 +107,7 @@ public class Players extends Listener {
}
private MutablePlayerListEntry getEntry (PlayerListS2CPacket.Entry other) {
return getEntry(other.profile().getId());
return getEntry(other.profileId());
}
private void addPlayer (PlayerListS2CPacket.Entry newEntry) {
@ -137,8 +137,8 @@ public class Players extends Listener {
if (accessor == null) return;
final PlayerListEntryAccessor entryAccessor = (PlayerListEntryAccessor) accessor.playerListEntries().get(newEntry.profile().getId());
if(entryAccessor == null) return;
final PlayerListEntryAccessor entryAccessor = (PlayerListEntryAccessor) accessor.playerListEntries().get(newEntry.profileId());
entryAccessor.setGameMode(newEntry.gameMode());
} catch (Exception e) {
//e.printStackTrace();
@ -155,9 +155,7 @@ public class Players extends Listener {
if (accessor == null) return;
final PlayerListEntryAccessor entryAccessor = (PlayerListEntryAccessor) accessor.playerListEntries().get(newEntry.profile().getId());
if(entryAccessor == null) return;
final PlayerListEntryAccessor entryAccessor = (PlayerListEntryAccessor) accessor.playerListEntries().get(newEntry.profileId());
entryAccessor.setLatency(newEntry.latency());
}
@ -171,9 +169,8 @@ public class Players extends Listener {
final ClientPlayNetworkHandlerAccessor accessor = ((ClientPlayNetworkHandlerAccessor) MinecraftClient.getInstance().getNetworkHandler());
if (accessor == null) return;
PlayerListEntry entry = accessor.playerListEntries().get(newEntry.profile().getId());
if(entry == null) return;
entry.setDisplayName(newEntry.displayName());
accessor.playerListEntries().get(newEntry.profileId()).setDisplayName(newEntry.displayName());
}
private void removePlayer (UUID uuid) {
@ -200,7 +197,7 @@ public class Players extends Listener {
final Message tooltip = suggestion.getTooltip();
if (tooltip != null || !suggestion.getText().equals(username)) continue;
return packet;
return true;
}
list.remove(target);
@ -213,7 +210,7 @@ public class Players extends Listener {
addToPlayerList(new PlayerListEntry(entry.profile, false));
}
return packet;
return true;
});
} catch (Exception e) {
//e.printStackTrace();

View file

@ -1,11 +1,11 @@
package land.chipmunk.chipmunkmod.modules;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.util.ColorUtilities;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayNetworkHandler;
@ -25,11 +25,11 @@ public class RainbowName {
public boolean enabled = false;
private String[] team;
public String displayName;
private int startHue = 0;
public double speed = 1;
public void init () {
final TimerTask task = new TimerTask() {
@ -90,11 +90,24 @@ public class RainbowName {
}
public void enable () {
final String[] colorCodes = generateColorCodes(8);
client.getNetworkHandler().sendChatCommand("extras:username " + generateUsername(colorCodes));
team = generateTeamName();
CommandCore.INSTANCE.run("minecraft:team add " + String.join("", team));
CommandCore.INSTANCE.run("minecraft:execute as " + client.getNetworkHandler().getProfile().getId() + " run team join " + String.join("", team));
enabled = true;
this.displayName = ChipmunkMod.CONFIG.defaultUsername;
}
public void disable () {
client.getNetworkHandler().sendChatCommand("extras:username " + client.getSession().getUsername());
CommandCore.INSTANCE.run("minecraft:team remove " + String.join("", team));
team = null;
CommandCore.INSTANCE.run("essentials:nick " + client.getSession().getUsername() + " off");
enabled = false;
@ -102,7 +115,7 @@ public class RainbowName {
public RainbowName (MinecraftClient client) {
this.client = client;
this.displayName = ChipmunkMod.CONFIG.defaultUsername;
this.displayName = client.getSession().getUsername();
}
private void tick () {
@ -115,8 +128,9 @@ public class RainbowName {
}
if (!enabled) return;
int hue = startHue;
int increment = (int) (360.0 / Math.max(displayName.length(), 20) * speed);
int increment = (int) (360.0 / Math.max(displayName.length(), 20));
Component component = Component.empty();
StringBuilder essentialsNickname = new StringBuilder();
@ -128,7 +142,8 @@ public class RainbowName {
hue = (hue + increment) % 360;
}
CommandCore.INSTANCE.run("essentials:nick " + ChipmunkMod.CONFIG.defaultUsername + " " + essentialsNickname);
CommandCore.INSTANCE.run("minecraft:team modify " + String.join("", team) + " prefix " + GsonComponentSerializer.gson().serialize(component));
CommandCore.INSTANCE.run("essentials:nick " + client.getSession().getUsername() + " " + essentialsNickname);
startHue = (startHue + increment) % 360;
} catch (Exception e) {

View file

@ -3,7 +3,6 @@ package land.chipmunk.chipmunkmod.modules;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.listeners.Listener;
import land.chipmunk.chipmunkmod.listeners.ListenerManager;
import land.chipmunk.chipmunkmod.testclient.modules.anti_annoyances.SelfCareModule;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.client.network.ClientPlayerEntity;
@ -87,8 +86,6 @@ public class SelfCare extends Listener {
hasSkin = false;
cspy = false;
// cspy too mabe?
// why was cspy not here lol
}
@Override
@ -106,22 +103,20 @@ public class SelfCare extends Listener {
}
public void tick () {
final ClientPlayerEntity player = client.player;
final ClientPlayNetworkHandler networkHandler = client.getNetworkHandler();
if (networkHandler == null) {
cleanup();
return;
}
if(!SelfCareModule.instance.isEnabled) return;
final ClientPlayerEntity player = client.player;
if (player != null && !player.hasPermissionLevel(2) && opEnabled) { if (serverHasCommand("op")) networkHandler.sendChatCommand("op @s[type=player]"); }
else if (gameMode != 1 && gamemodeEnabled) networkHandler.sendChatCommand("gamemode creative");
else if (positionPacketsPerSecond >= 10 && icuEnabled) CommandCore.INSTANCE.run("sudo * icu stop");
}
public void chatTick () {
if(!SelfCareModule.instance.isEnabled) return;
final ClientPlayNetworkHandler networkHandler = client.getNetworkHandler();
if (!cspy && cspyEnabled) { if (serverHasCommand("c")) networkHandler.sendChatCommand("c on"); }

View file

@ -5,6 +5,7 @@ import land.chipmunk.chipmunkmod.song.Song;
import land.chipmunk.chipmunkmod.song.SongLoaderException;
import land.chipmunk.chipmunkmod.song.SongLoaderThread;
import land.chipmunk.chipmunkmod.util.MathUtilities;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
@ -55,34 +56,34 @@ public class SongPlayer {
public void loadSong (Path location) {
if (loaderThread != null) {
client.player.sendMessage(Component.translatable("Already loading a song, cannot load another", NamedTextColor.RED));
((Audience) client.player).sendMessage(Component.translatable("Already loading a song, cannot load another", NamedTextColor.RED));
return;
}
try {
final SongLoaderThread _loaderThread = new SongLoaderThread(location);
client.player.sendMessage(Component.translatable("Loading %s", Component.text(location.getFileName().toString(), NamedTextColor.DARK_GREEN)).color(NamedTextColor.GREEN));
((Audience) client.player).sendMessage(Component.translatable("Loading %s", Component.text(location.getFileName().toString(), NamedTextColor.DARK_GREEN)).color(NamedTextColor.GREEN));
_loaderThread.start();
loaderThread = _loaderThread;
} catch (SongLoaderException e) {
client.player.sendMessage(Component.translatable("Failed to load song: %s", e.message).color(NamedTextColor.RED));
((Audience) client.player).sendMessage(Component.translatable("Failed to load song: %s", e.message.getString()).color(NamedTextColor.RED));
loaderThread = null;
}
}
public void loadSong (URL location) {
if (loaderThread != null) {
client.player.sendMessage(Component.translatable("Already loading a song, cannot load another", NamedTextColor.RED));
((Audience) client.player).sendMessage(Component.translatable("Already loading a song, cannot load another", NamedTextColor.RED));
return;
}
try {
final SongLoaderThread _loaderThread = new SongLoaderThread(location);
client.player.sendMessage(Component.translatable("Loading %s", Component.text(location.toString(), NamedTextColor.DARK_GREEN)).color(NamedTextColor.GREEN));
((Audience) client.player).sendMessage(Component.translatable("Loading %s", Component.text(location.toString(), NamedTextColor.DARK_GREEN)).color(NamedTextColor.GREEN));
_loaderThread.start();
loaderThread = _loaderThread;
} catch (SongLoaderException e) {
client.player.sendMessage(Component.translatable("Failed to load song: %s", e.message).color(NamedTextColor.RED));
((Audience) client.player).sendMessage(Component.translatable("Failed to load song: %s", e.message.getString()).color(NamedTextColor.RED));
loaderThread = null;
}
}
@ -102,19 +103,19 @@ public class SongPlayer {
if (loaderThread != null && !loaderThread.isAlive()) {
if (loaderThread.exception != null) {
client.player.sendMessage(Component.translatable("Failed to load song: %s", loaderThread.exception.message).color(NamedTextColor.RED));
((Audience) client.player).sendMessage(Component.translatable("Failed to load song: %s", loaderThread.exception.message.getString()).color(NamedTextColor.RED));
} else {
songQueue.add(loaderThread.song);
client.player.sendMessage(Component.translatable("Added %s to the song queue", Component.empty().append(loaderThread.song.name).color(NamedTextColor.DARK_GREEN)).color(NamedTextColor.GREEN));
((Audience) client.player).sendMessage(Component.translatable("Added %s to the song queue", Component.empty().append(loaderThread.song.name).color(NamedTextColor.DARK_GREEN)).color(NamedTextColor.GREEN));
}
loaderThread = null;
}
if (currentSong == null) {
if (songQueue.size() == 0) return;
if (songQueue.isEmpty()) return;
currentSong = songQueue.poll();
client.player.sendMessage(Component.translatable("Now playing %s", Component.empty().append(currentSong.name).color(NamedTextColor.DARK_GREEN)).color(NamedTextColor.GREEN));
((Audience) client.player).sendMessage(Component.translatable("Now playing %s", Component.empty().append(currentSong.name).color(NamedTextColor.DARK_GREEN)).color(NamedTextColor.GREEN));
currentSong.play();
}
@ -122,7 +123,7 @@ public class SongPlayer {
else ticksUntilPausedActionbar = 20;
try {
if (!useCore && actionbar) client.player.sendActionBar(generateActionbar());
if (!useCore && actionbar && client.player != null) ((Audience) client.player).sendActionBar(generateActionbar());
else if (actionbar) CommandCore.INSTANCE.run("title " + SELECTOR + " actionbar " + GsonComponentSerializer.gson().serialize(generateActionbar()));
} catch (Exception e) {
e.printStackTrace();
@ -133,7 +134,7 @@ public class SongPlayer {
handlePlaying();
if (currentSong.finished()) {
client.player.sendMessage(Component.translatable("Finished playing %s", Component.empty().append(currentSong.name).color(NamedTextColor.DARK_GREEN)).color(NamedTextColor.GREEN));
((Audience) client.player).sendMessage(Component.translatable("Finished playing %s", Component.empty().append(currentSong.name).color(NamedTextColor.DARK_GREEN)).color(NamedTextColor.GREEN));
currentSong = null;
}
}
@ -148,11 +149,11 @@ public class SongPlayer {
final ClientPlayerEntity player = client.player;
Component component = Component.empty()
.append(Component.translatable("%s", player.getName()).color(NamedTextColor.GREEN))
.append(Component.translatable("%s", player.getName().getString()).color(NamedTextColor.GREEN))
.append(Component.translatable(" | ", NamedTextColor.DARK_GRAY))
.append(Component.translatable("Now playing %s", Component.empty().append(currentSong.name).color(NamedTextColor.DARK_GREEN)).color(NamedTextColor.GREEN))
.append(Component.translatable(" | ", NamedTextColor.DARK_GRAY))
.append(Component.translatable("%s / %s", formatTime(currentSong.time).asComponent().color(NamedTextColor.GREEN), formatTime(currentSong.length).asComponent().color(NamedTextColor.GREEN)).color(NamedTextColor.GRAY))
.append(Component.translatable("%s / %s", formatTime(currentSong.time).color(NamedTextColor.GREEN), formatTime(currentSong.length).color(NamedTextColor.GREEN)).color(NamedTextColor.GRAY))
.append(Component.translatable(" | ", NamedTextColor.DARK_GRAY))
.append(Component.translatable("%s / %s", Component.text(currentSong.position, NamedTextColor.GREEN), Component.text(currentSong.size(), NamedTextColor.GREEN)).color(NamedTextColor.GRAY));
@ -177,16 +178,16 @@ public class SongPlayer {
return component;
}
public Text formatTime (long millis) {
public Component formatTime (long millis) {
final int seconds = (int) millis / 1000;
final String minutePart = String.valueOf(seconds / 60);
final String unpaddedSecondPart = String.valueOf(seconds % 60);
return Text.translatable(
return Component.translatable(
"%s:%s",
Text.literal(minutePart),
Text.literal(unpaddedSecondPart.length() < 2 ? "0" + unpaddedSecondPart : unpaddedSecondPart)
Component.text(minutePart),
Component.text(unpaddedSecondPart.length() < 2 ? "0" + unpaddedSecondPart : unpaddedSecondPart)
);
}

View file

@ -50,7 +50,7 @@ public class TabComplete extends Listener {
}
public void packetReceived (CommandSuggestionsS2CPacket packet) {
final CompletableFuture<CommandSuggestionsS2CPacket> future = transactions.get(packet.getCompletionId());
final CompletableFuture<CommandSuggestionsS2CPacket> future = transactions.get(packet.id());
if (future == null) return;
future.complete(packet);

View file

@ -1,183 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.gui;
import land.chipmunk.chipmunkmod.testclient.gui.components.Module;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.testclient.gui.components.Category;
import land.chipmunk.chipmunkmod.testclient.modules.anti_annoyances.AntiChatSpamModule;
import land.chipmunk.chipmunkmod.testclient.modules.anti_annoyances.SelfCareModule;
import land.chipmunk.chipmunkmod.testclient.modules.fun.RainbowNameModule;
import land.chipmunk.chipmunkmod.testclient.modules.lag_prevention.AntiParticleKickModule;
import land.chipmunk.chipmunkmod.testclient.modules.lag_prevention.AntiTextObfuscationLagModule;
import land.chipmunk.chipmunkmod.testclient.modules.lag_prevention.BlockGuardianParticlesModule;
import land.chipmunk.chipmunkmod.testclient.modules.anti_annoyances.AntiTeleportModule;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.Drawable;
import net.minecraft.client.gui.Element;
import net.minecraft.client.gui.Selectable;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.text.Text;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
public class
Gui extends Screen{
public static ArrayList<Category> categoryList = new ArrayList<>();
public static Gui gui;
public <T extends Element & Drawable & Selectable> void publicAddDrawableChild(T element) {
addDrawableChild(element);
}
public void publicRemove(Element child) {
remove(child);
}
public Gui() {
super(Text.literal("TestClient menu"));
AtomicInteger categoryX = new AtomicInteger(20);
AtomicInteger categoryY = new AtomicInteger(20);
categoryList.forEach(category -> {
category.setFullHeight(categoryY.get());
addDrawableChild(category); // adapt category to be buttons
category.setX(categoryX.get());
category.setY(categoryY.get());
// category.setWidth(Main.MC.textRenderer.getWidth(category.getMessage()) + 20);
ChipmunkMod.LOGGER.info("Created category " + category.getMessage().getString() + " at x " + categoryX.get() + "(" + category.getX() + ") and y " + categoryY + "(" + category.getY() + ") and is " + category.getWidth() + " wide and " + category.getFullHeight() + " high");
categoryX.addAndGet(category.getWidth() + 20);
if(categoryX.get() + category.getWidth() + 20 > MinecraftClient.getInstance().getWindow().getWidth()) {
categoryX.set(20);
categoryY.addAndGet(40); //TODO make a max height per row at some point
/* Something like:
+----------------------+
| #### ### #### ##### |
| //// /// ///// |
| /// |
| ### ##### ### |
| /// ///// |
| ///// |
| ///// |
+----------------------+
actually nvm its good as it is now
*/
}
AtomicInteger yPos = new AtomicInteger(category.getY());
if(category.isExtended) category.moduleList.forEach(module -> {
publicAddDrawableChild(module);
module.setX(category.getX());
module.setY(yPos.addAndGet(20));
module.setWidth(category.getWidth());
});
});
}
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
// this.renderBackground(matrices);
super.render(context, mouseX, mouseY, delta);
}
public static void open() {
gui = new Gui();
MinecraftClient.getInstance().setScreen(gui);
}
// private class ScreenGui extends LightweightGuiDescription {
// public ScreenGui() {
// int scale = Main.MC.options.getGuiScale().getValue();
// // create invisible panel
// root = new Root();
// // set it as root
// setRootPanel(root);
// // make panel size big as the screen
// root.setSize(Main.MC.getWindow().getWidth()/scale, Main.MC.getWindow().getHeight()/scale); // still broken but fuck it idc
// root.setInsets(Insets.ROOT_PANEL);
//
// // set initial positions for the buttons
// AtomicInteger categoryX = new AtomicInteger(20);
// AtomicInteger categoryY = new AtomicInteger(20);
// categoryList.forEach(category -> {
// category.setFullHeight(categoryY.get());
// root.add(category, categoryX.get(), categoryY.get());
// category.setWidth(Main.MC.textRenderer.getWidth(category.getLabel()) + 20);
//
// Main.LOGGER.info("Created category " + category.getLabel().getString() + " at x " + categoryX.get() + "(" + category.getX() + ") and y " + categoryY + "(" + category.getY() + ") and is " + category.getWidth() + " wide and " + category.getFullHeight() + " high");
// categoryX.addAndGet(category.getWidth() + 20);
// if(categoryX.get() + category.getWidth() + 20 > root.getWidth()) {
// categoryX.set(20);
// categoryY.addAndGet(40); //TODO make a max height per row at some point
// /* Something like:
// +----------------------+
// | #### ### #### ##### |
// | //// /// ///// |
// | /// |
// | ### ##### ### |
// | /// ///// |
// | ///// |
// | ///// |
// +----------------------+
// actually nvm its good as it is now
// */
// }
// });
//
// root.validate(this);
// }
// }
public static void refreshGui() {
gui = new Gui();
}
public static void initAutoRefresher() {
// ClientTickEvents.END_CLIENT_TICK.register(listener -> {
// int scale = Main.MC.options.getGuiScale().getValue();
//// scale = 1;
// if(
// Main.MC.getWindow().getWidth()/scale != gui.root.getWidth()
// || Main.MC.getWindow().getHeight()/scale != gui.root.getHeight()
// ) {
// Main.LOGGER.info("Refreshed GUI size because "
// + Main.MC.getWindow().getWidth()/scale
// + " != "
// + gui.root.getWidth()
// + " or "
// + Main.MC.getWindow().getHeight()/scale
// + " != "
// + gui.root.getHeight()
// );
// refreshGui();
// }
// });
}
public static void addComponents() {
new Category("Lag prevention")
.withModule(AntiParticleKickModule.instance) //TODO: make kick prevention module
.withModule(BlockGuardianParticlesModule.instance)
.withModule(AntiTextObfuscationLagModule.instance)
.register();
new Category("Anti annoyances")
.withModule(AntiChatSpamModule.instance)
.withModule(new AntiTeleportModule())
.withModule(SelfCareModule.instance)
.register();
new Category("Fun")
.withModule(RainbowNameModule.instance)
.register();
// new Category("OP")
// .withModule(AutoOpModule.instance) //TODO: make selfcare module
// .register();
}
}

View file

@ -1,45 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.gui;
import land.chipmunk.chipmunkmod.testclient.gui.components.Option;
import land.chipmunk.chipmunkmod.testclient.gui.components.Module;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.util.math.MatrixStack;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
public class OptionsScreen extends Screen {
public static int backgroundColor = 0x99000000;
ArrayList<Option<?>> optionList = new ArrayList<>();
public OptionsScreen(Module module) {
super(module.getMessage().copy().append("'s options"));
for (Option<?> option : module.optionList) {
optionList.add(option);
addDrawableChild(option.widget);
}
}
@Override
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
context.fill(40, 40, width-40, height-40, backgroundColor);
int textWidth = MinecraftClient.getInstance().textRenderer.getWidth(getTitle());
AtomicInteger lineY = new AtomicInteger(70);
AtomicInteger textY = new AtomicInteger(50);
context.drawTextWithShadow(MinecraftClient.getInstance().textRenderer, getTitle(), width/2 - textWidth/2, 50, 0xFFFFFFFF);
context.fill(45, lineY.get()-1, width-45, lineY.get(), 0x33FFFFFF);
for (Option<?> option : optionList) {
lineY.addAndGet(30);
context.drawTextWithShadow(MinecraftClient.getInstance().textRenderer, option.name, 50, textY.addAndGet(30), 0xFFFFFFFF);
context.fill(45, lineY.get()-1, width-45, lineY.get(), 0x33FFFFFF);
// drawHorizontalLine(matrices, 45, width-45, lineY.addAndGet(30), 0x33FFFFFF);
option.widget.setX(width - 50 - option.widget.getWidth());
option.widget.setY(textY.get() - ((option.widget.getHeight()-9)/2));
}
super.render(context, mouseX, mouseY, delta);
}
}

View file

@ -1,109 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.gui.components;
import com.google.gson.annotations.Expose;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.testclient.gui.Gui;
import land.chipmunk.chipmunkmod.util.Chat;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.Text;
import net.minecraft.util.math.MathHelper;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
public class Category extends ButtonWidget {
public ArrayList<Module> moduleList = new ArrayList<>();
public boolean isExtended;
private int fullHeight;
private int defaultColor = 0xAAAA0000;
private int hoveredColor = 0xCCCC0000;
public Category(String name) {
super(0, 0, 20, 20, Text.literal(name), widget -> {}, ButtonWidget.DEFAULT_NARRATION_SUPPLIER);
isExtended = false;
}
@Override
public void onPress() {
isExtended = !isExtended;
if(isExtended) ChipmunkMod.LOGGER.info("Extended " + getMessage().getString());
else ChipmunkMod.LOGGER.info("Contracted " + getMessage().getString());
// getModuleList();
AtomicInteger yPos = new AtomicInteger(getY());
moduleList.forEach(module -> {
if(isExtended) {
Gui.gui.publicAddDrawableChild(module);
module.setX(getX());
module.setY(yPos.addAndGet(20));
module.setWidth(getWidth());
}
else Gui.gui.publicRemove(module);
// give module same width as category
// module.setWidth(getWidth());
});
}
public int getFullHeight() {
return fullHeight;
}
public void setFullHeight(int fullHeight) {
this.fullHeight = fullHeight;
}
public void register() {
Gui.categoryList.add(this);
}
public Category withModule(Module module) {
int moduleWidth = MinecraftClient.getInstance().textRenderer.getWidth(module.getMessage())+16;
ChipmunkMod.LOGGER.info("Module (" + module.getMessage() +") width: " + moduleWidth);
ChipmunkMod.LOGGER.info("This width: " + width);
ChipmunkMod.LOGGER.info("Module width is larger than this width: " + (moduleWidth > width));
if(moduleWidth > width) width = moduleWidth;
ChipmunkMod.LOGGER.info("Width after: " + width);
moduleList.add(module);
return this;
}
public void getModuleList() {
Chat.send(this.getMessage().getString() + "'s modules: ");
moduleList.forEach(module -> {
Chat.send(" - " + module.getMessage().getString());
});
}
// @Override
// public void paint(MatrixStack matrices, int x, int y, int mouseX, int mouseY) {
// boolean hovered = (mouseX>=0 && mouseY>=0 && mouseX<getWidth() && mouseY<getHeight());
// boolean isHovered = false; //0 = regular, 1 = hovered.
// if (hovered || isFocused()) {
// isHovered = true;
// }
// // draw the box
// ScreenDrawing.coloredRect(matrices, x, y, getWidth(), getHeight(), isHovered ? hoveredColor : defaultColor);
//
// if (this.getLabel()!=null) {
// // draw the text
// int textColor = 0xE0E0E0;
// ScreenDrawing.drawStringWithShadow(matrices, this.getLabel().asOrderedText(), alignment, x, y + ((20 - 8) / 2), width, textColor);
// /* else if (hovered) {
// color = 0xFFFFA0;
// }*/
//
// // int xOffset = (icon != null && alignment == HorizontalAlignment.LEFT) ? ICON_SPACING+iconSize+ICON_SPACING : 0;
// }
// }
@Override
public void renderButton(DrawContext context, int mouseX, int mouseY, float delta) {
boolean hovered = (mouseX>=getX() && mouseY>=getY() && mouseX<getWidth()+getX() && mouseY<getHeight()+getY());
MinecraftClient minecraftClient = MinecraftClient.getInstance();
context.fill(getX(), getY(), getX()+getWidth(), getY()+getHeight(), hovered ? hoveredColor : defaultColor);
this.drawMessage(context, minecraftClient.textRenderer, 0xFFFFFF | MathHelper.ceil(this.alpha * 255.0F) << 24);
}
}

View file

@ -1,187 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.gui.components;
import com.google.gson.annotations.Expose;
import land.chipmunk.chipmunkmod.testclient.gui.OptionsScreen;
import land.chipmunk.chipmunkmod.util.TickRunnableHandler;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.Text;
import net.minecraft.util.math.MathHelper;
import java.util.ArrayList;
public class Module extends ButtonWidget {
public Runnable activateRunnable;
public Runnable deactivateRunnable;
public Runnable endTickRunnable;
public boolean needsInWorld = true;
public boolean isEnabled;
public static int defaultColor = 0xCC333333;
public static int hoveredColor = 0xEE444444;
public static int disabledBarColor = 0xAA000000;
public static int enabledBarColor = 0xEE00AA00;
public ArrayList<Option<?>> optionList = new ArrayList<>();
public Module(String name) {
super(0, 0, 20, 20, Text.literal(name), widget -> {}, ButtonWidget.DEFAULT_NARRATION_SUPPLIER);
isEnabled = false;
// optionsButton = new OptionsButton(this);
}
public Module withOption(Option<?> option) {
optionList.add(option);
return this;
}
// @Override
// public void onPress() {
//
// isEnabled = !isEnabled;
// if (isEnabled) {
// if (activateRunnable != null) activateRunnable.run();
// if (endTickRunnable != null) TickRunnableHandler.runAtTickEnd.add(endTickRunnable);
// } else {
// if (deactivateRunnable != null) deactivateRunnable.run();
// if (endTickRunnable != null) TickRunnableHandler.runAtTickEnd.remove(endTickRunnable);
// }
// }
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (this.active && this.visible && clicked(mouseX, mouseY)) {
if (button == 0) {
isEnabled = !isEnabled;
if (isEnabled) {
if (activateRunnable != null) activateRunnable.run();
if (endTickRunnable != null) TickRunnableHandler.runAtTickEnd.add(endTickRunnable);
} else {
if (deactivateRunnable != null) deactivateRunnable.run();
if (endTickRunnable != null) TickRunnableHandler.runAtTickEnd.remove(endTickRunnable);
}
return true;
} else if(button == 1) {
MinecraftClient.getInstance().setScreen(new OptionsScreen(this));
return true;
}
}
return false;
}
// void setWidth(int width) {
// this.width = width;
// }
// @Override
// public void renderButton(MatrixStack matrices, int mouseX, int mouseY, float delta) {
// MinecraftClient minecraftClient = MinecraftClient.getInstance();
// RenderSystem.setShaderTexture(0, WIDGETS_TEXTURE);
// RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, this.alpha);
// RenderSystem.enableBlend();
// RenderSystem.enableDepthTest();
// drawNineSlicedTexture(matrices, this.getX(), this.getY(), this.getWidth(), this.getHeight(), 20, 4, 200, 20, 0, this.getTextureY());
//
// RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
// int i = this.active ? 16777215 : 10526880;
// this.drawMessage(matrices, minecraftClient.textRenderer, i | MathHelper.ceil(this.alpha * 255.0F) << 24);
// }
// public void paint(MatrixStack matrices, int x, int y, int mouseX, int mouseY) {
// boolean hovered = (mouseX>=0 && mouseY>=0 && mouseX<getWidth() && mouseY<getHeight());
// boolean isHovered = false; //0 = regular, 1 = hovered.
// if (hovered || isFocused()) {
// isHovered = true;
// }
// // draw the box
// ScreenDrawing.coloredRect(matrices, x, y, getWidth(), getHeight(), isHovered ? hoveredColor : defaultColor);
// // draw enabled/disabled indicator
// ScreenDrawing.coloredRect(matrices, x, y, 2, getHeight(), isEnabled ? enabledBarColor : disabledBarColor);
//
//
// if (this.getLabel()!=null) {
// // draw the text
// int textColor = 0xE0E0E0;
// ScreenDrawing.drawStringWithShadow(matrices, this.getLabel().asOrderedText(), alignment, x+1 /* to make it offset to the indicator */, y + ((20 - 8) / 2), width, textColor);
// /* else if (hovered) {
// color = 0xFFFFA0;
// }*/
//
// // int xOffset = (icon != null && alignment == HorizontalAlignment.LEFT) ? ICON_SPACING+iconSize+ICON_SPACING : 0;
// }
// }
public Module onActivate(Runnable runnable) {
activateRunnable = runnable;
return this;
}
public Module onDeactivate(Runnable runnable) {
deactivateRunnable = runnable;
return this;
}
public Module atEndTick(Runnable runnable) {
endTickRunnable = runnable;
return this;
}
@Override
public void renderButton(DrawContext context, int mouseX, int mouseY, float delta) {
boolean hovered = (mouseX>=getX() && mouseY>=getY() && mouseX<getWidth()+getX() && mouseY<getHeight()+getY());
context.fill(getX(), getY(), getX()+getWidth(), getY()+getHeight(), hovered ? hoveredColor : defaultColor);
context.fill(getX(), getY(), getX()+2, getY()+getHeight(), isEnabled ? enabledBarColor : disabledBarColor);
drawMessage(context, MinecraftClient.getInstance().textRenderer, 0xFFFFFF | MathHelper.ceil(this.alpha * 255.0F) << 24);
}
// public static class OptionsButton extends WButton {
// public boolean isHovered = false;
// public Module parentModule;
// public OptionsButton(Module parent) {
// super(Text.of(""));
// setSize(20, 20);
// parentModule = parent;
// setOnClick(() -> {
// int scale = Main.MC.options.getGuiScale().getValue();
// Gui.gui.root.add(new OptionsPanel(parentModule), 10, 10, (Main.MC.getWindow().getWidth()/scale)-40, (Main.MC.getWindow().getHeight()/scale)-40);
// });
// }
//
//
// private final int defaultColor = 0x00333333;
// private final int hoveredColor = 0xEE777777;
//
// @Override
// public void paint(MatrixStack matrices, int x, int y, int mouseX, int mouseY) {
// boolean hovered = (mouseX>=0 && mouseY>=0 && mouseX<getWidth() && mouseY<getHeight());
// isHovered = false; //0 = regular, 1 = hovered.
// if (hovered || isFocused()) {
// isHovered = true;
// }
// // draw the box
// ScreenDrawing.coloredRect(matrices, x, y, getWidth(), getHeight(), isHovered ? hoveredColor : defaultColor);
//
//
// if (this.getLabel()!=null) {
// // draw the text
// int textColor = 0xE0E0E0;
// ScreenDrawing.drawStringWithShadow(matrices, this.getLabel().asOrderedText(), alignment, x, y + ((20 - 8) / 2), width, textColor);
// /* else if (hovered) {
// color = 0xFFFFA0;
// }*/
//
// // int xOffset = (icon != null && alignment == HorizontalAlignment.LEFT) ? ICON_SPACING+iconSize+ICON_SPACING : 0;
// }
// }
//
//
//
// }
}
/*
TODO:
- finish translating Module from WButton to vanilla ButtonWidget
- translate categories from WButton to vanilla ButtonWidget
- make everything work with vanilla stuff
The goal is to stop struggling with screen size. It's so annoying with LibGui.
*/

View file

@ -1,21 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.gui.components;
import land.chipmunk.chipmunkmod.memory.ModuleMemory;
import net.minecraft.client.gui.widget.ClickableWidget;
public abstract class Option<ValueType> {
public String name;
public ValueType optionValue;
public ClickableWidget widget;
public Option(String name, ValueType defaultValue) {
this.name = name;
optionValue = defaultValue;
}
public ModuleMemory.Option<ValueType> toMemoryOption() {return new ModuleMemory.Option<>(name, optionValue);}
public Class<ValueType> getType() {return (Class<ValueType>) optionValue.getClass();} // ignore this error intellij has the stupid
public abstract void setValueFromString(String string);
public abstract String getValueAsString();
// these two should match perfectly, meaning that setValueFromString(getValueAsString()); should do nothing
}

View file

@ -1,54 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.gui.components.options;
import land.chipmunk.chipmunkmod.testclient.gui.components.Option;
import net.minecraft.client.gui.widget.CheckboxWidget;
import net.minecraft.client.gui.widget.SliderWidget;
import net.minecraft.text.Text;
import java.lang.reflect.Field;
public class BooleanCheckboxOption extends Option<Boolean> {
private RunnableWithParameter<Boolean> onPress = value -> {};
CheckboxWidget checkboxWidget = new CheckboxWidget(0, 0, 20, 20, Text.empty(), optionValue) {
@Override
public void onPress() {
optionValue = !optionValue;
onPress.run(optionValue);
// equivalent of `checked = optionValue`, but checked is private so i have to use this :(
try {
Field checked = CheckboxWidget.class.getDeclaredField("checked");
checked.setAccessible(true);
checked.set(this, optionValue);
} catch(NoSuchFieldException | IllegalAccessException e) {e.printStackTrace();}
}
};
public BooleanCheckboxOption(String name, boolean defaultValue) {
super(name, defaultValue);
optionValue = defaultValue;
widget = checkboxWidget;
}
public BooleanCheckboxOption(String name, boolean defaultValue, RunnableWithParameter<Boolean> onPress) {
super(name, defaultValue);
optionValue = defaultValue;
widget = checkboxWidget;
this.onPress = onPress;
}
@Override
public void setValueFromString(String string) {
optionValue = Boolean.valueOf(string);
}
@Override
public String getValueAsString() {
return Boolean.toString(optionValue);
}
public interface RunnableWithParameter<T> {
void run(T value);
}
}

View file

@ -1,63 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.gui.components.options;
import land.chipmunk.chipmunkmod.testclient.gui.components.Option;
import net.minecraft.client.gui.widget.SliderWidget;
import net.minecraft.text.Text;
public class DoubleSliderOption extends Option<Double> {
public double maxValue = 100;
public double minValue = 0;
int roundTo = 4;
SliderWidget sliderWidget = new SliderWidget(0, 0, 100, 20, Text.literal("text ig"), 0.0) {
@Override
protected void updateMessage() {
setMessage(Text.literal(round((value * (maxValue - minValue) + minValue), roundTo)+""));
}
@Override
protected void applyValue() {
optionValue = round((value * (maxValue - minValue) + minValue), roundTo);
}
public double getValue() {
return value;
}
};
public DoubleSliderOption(String name, double defaultValue) {
super(name, defaultValue);
optionValue = defaultValue;
widget = sliderWidget;
}
public DoubleSliderOption(String name, double defaultValue, double minValue, double maxValue) {
super(name, defaultValue);
optionValue = defaultValue;
widget = sliderWidget;
this.minValue = minValue;
this.maxValue = maxValue;
}
public DoubleSliderOption(String name, double defaultValue, double minValue, double maxValue, int round) {
super(name, defaultValue);
optionValue = defaultValue;
widget = sliderWidget;
this.minValue = minValue;
this.maxValue = maxValue;
roundTo = round;
}
public static double round(double value, int places) {
if (places < 0) return value;
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
public void setValueFromString(String string) {
optionValue = Double.valueOf(string);
}
public String getValueAsString() {
return Double.toString(optionValue);
}
}

View file

@ -1,48 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.gui.components.options;
import land.chipmunk.chipmunkmod.testclient.gui.components.Option;
import net.minecraft.client.gui.widget.SliderWidget;
import net.minecraft.text.Text;
public class IntSliderOption extends Option<Integer> {
public int maxValue = 100;
public int minValue = 0;
SliderWidget sliderWidget = new SliderWidget(0, 0, 100, 20, Text.literal("text ig"), 0.0) {
@Override
protected void updateMessage() {
setMessage(Text.literal(((int) (value * (maxValue - minValue) + minValue))+""));
}
@Override
protected void applyValue() {
optionValue = (int) (value * (maxValue - minValue) + minValue);
}
public double getValue() {
return value;
}
};
public IntSliderOption(String name, int defaultValue) {
super(name, defaultValue);
optionValue = defaultValue;
widget = sliderWidget;
}
public IntSliderOption(String name, int defaultValue, int minValue, int maxValue) {
super(name, defaultValue);
optionValue = defaultValue;
widget = sliderWidget;
this.minValue = minValue;
this.maxValue = maxValue;
}
@Override
public void setValueFromString(String string) {
optionValue = Integer.valueOf(string);
}
@Override
public String getValueAsString() {
return Integer.toString(optionValue);
}
}

View file

@ -1,41 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.gui.components.options;
import land.chipmunk.chipmunkmod.testclient.gui.components.Option;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.text.Text;
import java.util.function.Consumer;
public class StringOption extends Option<String> {
TextFieldWidget textFieldWidget = new TextFieldWidget(MinecraftClient.getInstance().textRenderer, 0, 0, 200, 20, Text.empty());
public StringOption(String name, String defaultValue) {
super(name, defaultValue);
textFieldWidget.setText(defaultValue);
textFieldWidget.setChangedListener(text -> {
optionValue = text;
});
widget = textFieldWidget;
}
public StringOption(String name, String defaultValue, Consumer<String> onChanged) {
super(name, defaultValue);
textFieldWidget.setText(defaultValue);
textFieldWidget.setChangedListener(text -> {
optionValue = text;
onChanged.accept(text);
});
widget = textFieldWidget;
}
@Override
public void setValueFromString(String string) {
optionValue = string; // pro conversion
}
@Override
public String getValueAsString() {
return optionValue;
}
}

View file

@ -1,81 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.modules.anti_annoyances;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.testclient.gui.components.Module;
import land.chipmunk.chipmunkmod.util.Debug;
import lombok.Getter;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.minecraft.text.Text;
import org.apache.commons.text.similarity.LevenshteinDistance;
import java.util.ArrayList;
public class AntiChatSpamModule extends Module {
public static Text latestPassedThroughMessage = Text.empty();
public static AntiChatSpamModule instance = new AntiChatSpamModule();
public ArrayList<ChatMessage> messages = new ArrayList<>();
private static final String debugCallerPrefix = "AntiChatSpam.";
private static final String debugTickedCaller = debugCallerPrefix + "tick";
private static final String debugLevenshteinDistanceCaller = debugCallerPrefix + "levenshtein_distance";
private static final String debugLevenshteinDistanceCallerSpamless = debugCallerPrefix + "levenshtein_distance_spamless";
public AntiChatSpamModule() {
super("Anti chat spam");
isEnabled = true;
ClientTickEvents.END_CLIENT_TICK.register(client -> {
// ChipmunkMod.LOGGER.info("gex");
for (int i = 0; i < messages.size(); i++) {
if(messages.get(i) == null) continue;
Debug.debug("Ticked message: " + messages.get(i).content, debugTickedCaller);
messages.get(i).tick();
}
});
}
public static class ChatMessage {
private @Getter final String content;
public boolean hidden = false;
public int timer = ChipmunkMod.CONFIG.antiSpam.messageTimeInTicks;
public ChatMessage(String content) {
this.content = content;
ArrayList<ChatMessage> chatMessages = instance.messages;
int similarMessages = 0;
LevenshteinDistance ld = new LevenshteinDistance(); // thanks maniaplay fo r teaching me about levenshtein distance
for (int i = 0; i < chatMessages.size(); i++) {
ChatMessage message = chatMessages.get(i);
if(message == null) continue;
int distance = ld.apply(content, message.content);
Debug.debug("Distance: " + distance, debugLevenshteinDistanceCaller);
if (distance <= ChipmunkMod.CONFIG.antiSpam.minimumLevenshteinDistanceToBeSpam) similarMessages++;
// Pattern pattern = getPattern(new ComparableString(this.content()), new ComparableString(message.content()));
// int matching = 0;
// ArrayList<ChatMessage> chatMessageArrayList = instance.messages;
// for (int j = 0; j < chatMessageArrayList.size(); j++) {
// ChatMessage message1 = chatMessageArrayList.get(j);
// if (pattern.matcher(message1.content()).matches()) matching++;
// }
// if (matching >= ChipmunkMod.CONFIG.antiSpam.matchingMessagesToBeSpam) {
// instance.patterns.add(new BlockedPattern(pattern));
// }
}
Debug.debug("Similar messages: " + similarMessages, debugLevenshteinDistanceCaller);
Debug.debug("Similar messages: " + similarMessages, debugLevenshteinDistanceCallerSpamless);
if (similarMessages >= ChipmunkMod.CONFIG.antiSpam.matchingMessagesToBeSpam) hidden = true;
Debug.debug("Hidden: " + hidden, debugLevenshteinDistanceCaller);
Debug.debug("Hidden: " + hidden, debugLevenshteinDistanceCallerSpamless);
instance.messages.add(this);
// threadQueue.add(() -> {
// // code above used to be here but i cant decide if i should show it or not depending on the thread cuz i cant make it wait
// });
}
public void tick() {
timer--;
if (timer <= 0) instance.messages.remove(this);
}
}
}

View file

@ -1,53 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.modules.anti_annoyances;
import land.chipmunk.chipmunkmod.testclient.gui.components.Module;
import land.chipmunk.chipmunkmod.util.Chat;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.math.Vec3d;
public class AntiTeleportModule extends Module {
private static Vec3d previousPos;
private static Vec3d currentPos;
public static int timer = 0;
public AntiTeleportModule() {
super("AntiTP");
endTickRunnable = new Runnable() {
@Override
public void run() {
if(MinecraftClient.getInstance().player != null) {
currentPos = MinecraftClient.getInstance().player.getPos();
if(previousPos == null) {
previousPos = currentPos;
return;
}
if(getDistance(currentPos, previousPos) > 10 && timer <= 0) {
String command = "tp "+previousPos.x+" "+previousPos.y+" "+previousPos.z;
MinecraftClient.getInstance().player.networkHandler.sendChatCommand(command);
// Chat.send("[AntiTP] Ran `" + command + "`");
timer = 10;
}
previousPos = currentPos;
timer--;
}
}
};
isEnabled = true;
}
public double getDistance(Vec3d first, Vec3d second) {
double distanceX = 0, distanceY = 0, distanceZ = 0;
distanceX = first.x - second.x;
if(distanceX<0) distanceX = -distanceX;
distanceY = first.y - second.y;
if(distanceY<0) distanceY = -distanceY;
distanceZ = first.z - second.z;
if(distanceZ<0) distanceZ = -distanceZ;
return distanceX + distanceY + distanceZ;
}
}

View file

@ -1,52 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.modules.anti_annoyances;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.modules.SelfCare;
import land.chipmunk.chipmunkmod.testclient.gui.components.Module;
import land.chipmunk.chipmunkmod.testclient.gui.components.options.BooleanCheckboxOption;
import land.chipmunk.chipmunkmod.testclient.gui.components.options.StringOption;
public class SelfCareModule extends Module {
public static SelfCareModule instance = new SelfCareModule();
BooleanCheckboxOption opOption = new BooleanCheckboxOption(
"OP",
SelfCare.INSTANCE.opEnabled,
value -> SelfCare.INSTANCE.opEnabled = value
);
BooleanCheckboxOption gmcOption = new BooleanCheckboxOption(
"Creative mode",
SelfCare.INSTANCE.gamemodeEnabled,
value -> SelfCare.INSTANCE.gamemodeEnabled = value
);
BooleanCheckboxOption cspyOption = new BooleanCheckboxOption(
"Command spy",
SelfCare.INSTANCE.cspyEnabled,
value -> SelfCare.INSTANCE.cspyEnabled = value
);
StringOption skinUsernameOption = new StringOption(
"Skin's username",
ChipmunkMod.CONFIG.defaultUsername,
s -> {
SelfCare.INSTANCE.hasSkin = false;
}
);
BooleanCheckboxOption skinOption = new BooleanCheckboxOption(
"Skin",
SelfCare.INSTANCE.skin.equals("off")
// value -> {
// SelfCare.INSTANCE.skin = value ? skinUsernameOption.optionValue : "off";
// }
);
public SelfCareModule() {
super("Self care");
withOption(opOption);
withOption(gmcOption);
withOption(cspyOption);
withOption(skinOption);
withOption(skinUsernameOption);
endTickRunnable = () -> {
// make it update the skin self acre username
SelfCare.INSTANCE.skin = skinOption.optionValue ? skinUsernameOption.optionValue : "off";
};
}
}

View file

@ -1,23 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.modules.fun;
import land.chipmunk.chipmunkmod.modules.RainbowName;
import land.chipmunk.chipmunkmod.testclient.gui.components.Module;
import land.chipmunk.chipmunkmod.testclient.gui.components.options.DoubleSliderOption;
public class RainbowNameModule extends Module {
public static RainbowNameModule instance = new RainbowNameModule();
public static DoubleSliderOption speedOption;
public RainbowNameModule() {
super("Rainbow name");
speedOption = new DoubleSliderOption("Speed", 1, 0.1, 2, 2);
withOption(speedOption);
needsInWorld = true;
// onActivate(RainbowName.INSTANCE::enable);
onDeactivate(RainbowName.INSTANCE::disable);
atEndTick(() -> {
RainbowName.INSTANCE.enable();
RainbowName.INSTANCE.speed = speedOption.optionValue;
});
}
}

View file

@ -1,13 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.modules.lag_prevention;
import land.chipmunk.chipmunkmod.testclient.gui.components.Module;
public class AntiParticleKickModule extends Module {
public static AntiParticleKickModule instance = new AntiParticleKickModule();
public AntiParticleKickModule() {
super("Anti particle crash");
isEnabled = true;
}
}

View file

@ -1,15 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.modules.lag_prevention;
import land.chipmunk.chipmunkmod.testclient.gui.components.Module;
import java.time.Instant;
public class AntiTextObfuscationLagModule extends Module {
public static AntiTextObfuscationLagModule instance = new AntiTextObfuscationLagModule();
public Instant renderTimeStart = Instant.now();
public boolean exceededLimitThisTick = false;
public AntiTextObfuscationLagModule() {
super("Anti Text Obfuscation");
isEnabled = true;
}
}

View file

@ -1,19 +0,0 @@
package land.chipmunk.chipmunkmod.testclient.modules.lag_prevention;
import land.chipmunk.chipmunkmod.testclient.gui.components.Module;
import land.chipmunk.chipmunkmod.testclient.gui.components.options.StringOption;
import land.chipmunk.chipmunkmod.util.Chat;
public class BlockGuardianParticlesModule extends Module {
public static BlockGuardianParticlesModule instance = new BlockGuardianParticlesModule();
public BlockGuardianParticlesModule() {
super("No guardian particles");
isEnabled = true;
withOption(new StringOption("Message", "Test option"));
activateRunnable = () -> {
Chat.send("" + optionList.get(0).optionValue);
};
}
}

View file

@ -1,9 +0,0 @@
package land.chipmunk.chipmunkmod.util;
import java.util.Arrays;
public class ArrayUtil {
public static String[] removeFirst(String[] original,int index) {
return Arrays.stream(original).toList().subList(index, original.length).toArray(new String[0]);
}
}

View file

@ -115,6 +115,54 @@ public class BotValidationUtilities {
return Command.SINGLE_SUCCESS;
}
public static int chomens (String command) throws RuntimeException {
final Configuration.ChomeNSBotInfo info = ChipmunkMod.CONFIG.bots.chomens;
final MinecraftClient client = MinecraftClient.getInstance();
final ClientPlayerEntity player = client.player;
final String prefix = info.prefix;
final String key = info.key;
if (key == null) throw new RuntimeException("The key of the bot is unspecified (null), did you incorrectly add it to your config?");
try {
String[] arguments = command.split(" ");
MessageDigest md = MessageDigest.getInstance("SHA-256");
String time = String.valueOf(System.currentTimeMillis() / 5_000);
String input = client.player.getUuidAsString() + arguments[0] + time + key;
byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
String stringHash = Hexadecimal.encode(hash).substring(0, 16);
final boolean shouldSectionSign = CustomChat.INSTANCE.enabled && player.hasPermissionLevel(2) && player.isCreative();
if (shouldSectionSign) {
stringHash = String.join("",
Arrays.stream(stringHash.split(""))
.map((letter) -> "§" + letter)
.toArray(String[]::new)
);
}
final String[] restArguments = Arrays.copyOfRange(arguments, 1, arguments.length);
final String toSend = prefix +
arguments[0] +
" " +
stringHash +
(shouldSectionSign ? "§r" : "") +
" " +
String.join(" ", restArguments);
Chat.sendChatMessage(toSend);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return Command.SINGLE_SUCCESS;
}
public static int kittycorp (String command) throws RuntimeException {
final Configuration.BotInfo info = ChipmunkMod.CONFIG.bots.kittycorp;
final ClientPlayNetworkHandler networkHandler = MinecraftClient.getInstance().getNetworkHandler();

View file

@ -1,30 +0,0 @@
package land.chipmunk.chipmunkmod.util;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import net.minecraft.client.MinecraftClient;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import java.time.Instant;
import java.util.Random;
public class Chat {
public static final MinecraftClient MC = MinecraftClient.getInstance();
public static void send(String message) {
MC.inGameHud.getChatHud().addMessage(Text.of(message));
}
public static void send(Text message) {
MC.inGameHud.getChatHud().addMessage(message);
}
public static void sendRed(String message) {
send(Text.literal(message).formatted(Formatting.RED));
}
public static void sendGreen(String message) {
send(Text.literal(message).formatted(Formatting.GREEN));
}
public static void sendGold(String message) {
send(Text.literal(message).formatted(Formatting.GOLD));
}
}

View file

@ -1,14 +0,0 @@
package land.chipmunk.chipmunkmod.util;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import java.util.ArrayList;
public class Debug {
public static ArrayList<String> known = new ArrayList<>();
public static ArrayList<String> selected = new ArrayList<>();
public static void debug(String string, String caller) {
if(selected.contains(caller)) ChipmunkMod.LOGGER.info(String.format("[DEBUG|%s] %s", caller, string));
if(!known.contains(caller)) known.add(caller);
}
}

View file

@ -1,17 +0,0 @@
package land.chipmunk.chipmunkmod.util;
import jdk.jshell.JShell;
public class Eval {
public static JShell shell = JShell.create();
public static void shell(String code) {
shell.eval(code);
}
static {
shell.onSnippetEvent(event -> {
Chat.sendGold(event.value());
});
}
}

View file

@ -1,13 +0,0 @@
package land.chipmunk.chipmunkmod.util;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Executor {
public static ExecutorService service = Executors.newFixedThreadPool(20);
public static ExecutorService antiChatSpamService = Executors.newFixedThreadPool(1);
public static Future<?> submit(Runnable runnable) {
return service.submit(runnable);
}
}

View file

@ -1,45 +0,0 @@
package land.chipmunk.chipmunkmod.util;
import land.chipmunk.chipmunkmod.testclient.gui.Gui;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFW;
public class Keybinds {
private static KeyBinding testKeyBinding;
private static KeyBinding delayPacketsKeyBinding;
private static KeyBinding openGuiKeyBinding;
public static void registerTest() {
// create the keybind
testKeyBinding = KeyBindingHelper.registerKeyBinding(new KeyBinding(
"key.test_client.test", // the translation key for the keybind itself
InputUtil.Type.KEYSYM, // KEYSYM for keyboard, MOUSE for mouse
GLFW.GLFW_KEY_RIGHT_SHIFT, // the key
"category.test_client.test" // The translation key for the keybind category
));
// register it
ClientTickEvents.END_CLIENT_TICK.register(client -> {
while (testKeyBinding.wasPressed()) {
// here goes the code that gets executed when it's pressed
Chat.send("Test button has been pressed!");
}
});
}
public static void registerOpenGui() {
// create the keybind
openGuiKeyBinding = KeyBindingHelper.registerKeyBinding(new KeyBinding(
"key.test_client.open_gui", // the translation key for the keybind itself
InputUtil.Type.KEYSYM, // KEYSYM for keyboard, MOUSE for mouse
GLFW.GLFW_KEY_RIGHT_SHIFT, // the key
"category.test_client.test_client" // The translation key for the keybind category
));
// register it
ClientTickEvents.END_CLIENT_TICK.register(client -> {
while (openGuiKeyBinding.wasPressed()) {
Gui.open();
}
});
}
}

View file

@ -1,12 +0,0 @@
package land.chipmunk.chipmunkmod.util;
import net.minecraft.server.MinecraftServer;
/**
* This class is used when there isn't a specific class where you'd store a variable, but you still need it somewhere.
* It's mostly used by mixins which can't hold public variables themselves.
*/
public class SharedVariables {
public static MinecraftServer serverConnectedTo = null;
public static int elderGuardianParticleTimer = 0;
}

View file

@ -0,0 +1,16 @@
package land.chipmunk.chipmunkmod.util;
import com.google.common.base.Suppliers;
import net.minecraft.registry.DynamicRegistryManager;
import net.minecraft.registry.Registries;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
public class TextUtilities {
public static MutableText fromJson (String json) {
return Text.Serialization.fromJson(
json,
Suppliers.ofInstance(DynamicRegistryManager.of(Registries.REGISTRIES)).get()
);
}
}

View file

@ -1,28 +0,0 @@
package land.chipmunk.chipmunkmod.util;
import land.chipmunk.chipmunkmod.testclient.gui.Gui;
import land.chipmunk.chipmunkmod.testclient.gui.components.Category;
import land.chipmunk.chipmunkmod.testclient.gui.components.Module;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.minecraft.client.MinecraftClient;
import java.util.ArrayList;
public class TickRunnableHandler {
public static ArrayList<Runnable> runAtTickEnd = new ArrayList<>();
public static void registerTickEndRunnables() {
ClientTickEvents.END_CLIENT_TICK.register(client -> {
for (Category category : Gui.categoryList) {
for (Module module : category.moduleList) {
if(module.isEnabled) {
if(
(!module.needsInWorld || MinecraftClient.getInstance().player != null)
&& module.endTickRunnable != null
) module.endTickRunnable.run();
}
}
}
});
}
}

View file

@ -1,39 +0,0 @@
package land.chipmunk.chipmunkmod.util;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import javax.net.ssl.HttpsURLConnection;
import java.awt.*;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.*;
/**
* unskidded 25/07/2023
*/
public class Webhook {
public static void send(String surl, String message) throws IOException {
Gson gson = new Gson();
JsonObject obj = new JsonObject();
URL url = new URL(surl);
obj.addProperty("content", message);
obj.addProperty("username", "chipmunkmod 7cc5c4f330d47060 fork (uwu)");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.4; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 ChipmunkMod/1.0.0 Safari/537.36");
connection.addRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
final OutputStream stream = connection.getOutputStream();
stream.write(obj.toString().getBytes());
stream.flush();
stream.close();
connection.getInputStream().close();
}
}

View file

@ -1,55 +0,0 @@
package land.chipmunk.chipmunkmod.util;
import net.minecraft.block.Block;
import net.minecraft.client.MinecraftClient;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
public class WorldUtil {
private static Block blockBreaking = null;
private static MinecraftClient MC = MinecraftClient.getInstance();
public static Block getBlockBreaking() {
return blockBreaking;
}
public static void setBlockBreaking(Block block) {
blockBreaking = block;
}
public static Block getBlockLooking() {
Vec3d pos = MinecraftClient.getInstance().crosshairTarget.getPos();
BlockPos blockPos = BlockPos.ofFloored(pos.x, pos.y, pos.z);
if(MC.world.getBlockState(blockPos) != null) return MC.world.getBlockState(blockPos).getBlock();
return null; // only if this is called while not in a world
}
public static double getPlayerDistance(Vec3d position) {
// crash-proof
if(MinecraftClient.getInstance().player == null) return 0;
Vec3d playerPos = MinecraftClient.getInstance().player.getPos();
double distanceX, distanceY, distanceZ;
distanceX = position.x - playerPos.x;
if(distanceX<0) distanceX = -distanceX;
distanceY = position.y - playerPos.y;
if(distanceY<0) distanceY = -distanceY;
distanceZ = position.z - playerPos.z;
if(distanceZ<0) distanceZ = -distanceZ;
return distanceX + distanceY + distanceZ;
}
public static boolean isPlayerOP() {
if(SharedVariables.serverConnectedTo==null) return false;
Chat.send(SharedVariables.serverConnectedTo.getOpPermissionLevel()+"");
return SharedVariables.serverConnectedTo.getOpPermissionLevel() > 0;
}
public static boolean isPlayerOP(MinecraftServer server) {
if(server==null) return false;
Chat.send(server.getOpPermissionLevel()+"");
return server.getOpPermissionLevel() > 0;
}
}

View file

@ -2,33 +2,22 @@
"required": true,
"minVersion": "0.8",
"package": "land.chipmunk.chipmunkmod.mixin",
"compatibilityLevel": "JAVA_17",
"compatibilityLevel": "JAVA_21",
"client": [
"ChatHudMixin",
"ChatInputSuggestorMixin",
"ChatScreenMixin",
"ClientConnectionAccessor",
"ClientConnectionInvoker",
"ClientConnectionMixin",
"ClientPlayerEntityMixin",
"ClientPlayNetworkHandlerAccessor",
"ClientPlayNetworkHandlerMixin",
"DecoratedPotBlockEntitySherdsMixin",
"MinecraftClientAccessor",
"StringHelperMixin",
"ElderGuardianAppearanceParticleMixin",
"FontStorageMixin",
"IdentifierMixin",
"KeyboardInputMixin",
"KeyboardMixin",
"MinecraftClientAccessor",
"MultiplayerScreenMixin",
"PlayerListEntryAccessor",
"SessionMixin",
"SharedConstantsMixin",
"StringHelperMixin",
"TextMixin",
"TitleScreenMixin",
"ClientConnectionInvoker",
"ClientConnectionAccessor",
"PlayerListEntryAccessor",
"TextSerializerMixin",
"CommandDispatcherMixin",
"SoundSystemMixin",
@ -38,8 +27,6 @@
"defaultRequire": 1
},
"mixins": [
"PacketBundleHandlerMixin",
"PlayerEntityMixin",
"TextMixin",
"TextSerializerMixin"
]

View file

@ -8,7 +8,6 @@
"authors": [
"_ChipMC_",
"chayapak",
"Blackilykat",
"7cc5c4f330d47060"
],
"contact": {
@ -31,9 +30,12 @@
],
"depends": {
"fabricloader": ">=0.14.21",
"fabricloader": ">=0.16.5",
"fabric-api": "*",
"minecraft": ">1.20",
"java": ">=17"
"minecraft": ">=1.21",
"java": ">=21"
},
"suggests": {
"another-mod": "*"
}
}