chams module

chams: Minecraft 26.3 cheat module, full source for every implementation (5 clients: Meteor Client, MelaHack (ThunderHack fork), OfflineClient, …).

5 implementationsRenderRENDERVISUALS

Full module source: 5 implementations

Every implementation below is the complete module file, verbatim. Expand a client to read its code.

Meteor ClientRendersrc/main/java/meteordevelopment/meteorclient/systems/modules/render/Chams.javaJava · 194 lines · 6.2 KB

Tweaks rendering of entities.

Settingsentitiesshadercolorignore-selfplayerstexturescalecrystalsbouncerotation-speedcrystal-colorenabledhand-color
Chams.javaJava · Minecraft 26.2 · 194 lines · 6.2 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Meteor Client distribution (https://github.com/MeteorDevelopment/meteor-client).
3
 * Copyright (c) Meteor Development.
4
 */
5
6
package meteordevelopment.meteorclient.systems.modules.render;
7
8
import meteordevelopment.meteorclient.MeteorClient;
9
import meteordevelopment.meteorclient.settings.*;
10
import meteordevelopment.meteorclient.systems.modules.Categories;
11
import meteordevelopment.meteorclient.systems.modules.Module;
12
import meteordevelopment.meteorclient.utils.render.color.SettingColor;
13
import net.minecraft.world.entity.Entity;
14
import net.minecraft.world.entity.EntityType;
15
import net.minecraft.resources.Identifier;
16
17
import java.util.Set;
18
19
public class Chams extends Module {
20
    private final SettingGroup sgThroughWalls = settings.createGroup("Through Walls");
21
    private final SettingGroup sgPlayers = settings.createGroup("Players");
22
    private final SettingGroup sgCrystals = settings.createGroup("Crystals");
23
    private final SettingGroup sgHand = settings.createGroup("Hand");
24
25
    // Through walls
26
27
    public final Setting<Set<EntityType<?>>> entities = sgThroughWalls.add(new EntityTypeListSetting.Builder()
28
        .name("entities")
29
        .description("Select entities to show through walls.")
30
        .onlyAttackable()
31
        .build()
32
    );
33
34
    public final Setting<Shader> shader = sgThroughWalls.add(new EnumSetting.Builder<Shader>()
35
        .name("shader")
36
        .description("Renders a shader over of the entities.")
37
        .defaultValue(Shader.Image)
38
        .build()
39
    );
40
41
    public final Setting<SettingColor> shaderColor = sgThroughWalls.add(new ColorSetting.Builder()
42
        .name("color")
43
        .description("The color that the shader is drawn with.")
44
        .defaultValue(new SettingColor(255, 255, 255, 150))
45
        .visible(() -> shader.get() != Shader.None)
46
        .build()
47
    );
48
49
    public final Setting<Boolean> ignoreSelfDepth = sgThroughWalls.add(new BoolSetting.Builder()
50
        .name("ignore-self")
51
        .description("Ignores yourself drawing the player.")
52
        .defaultValue(true)
53
        .build()
54
    );
55
56
    // Players
57
58
    public final Setting<Boolean> players = sgPlayers.add(new BoolSetting.Builder()
59
        .name("players")
60
        .description("Enables model tweaks for players.")
61
        .defaultValue(false)
62
        .build()
63
    );
64
65
    public final Setting<Boolean> ignoreSelf = sgPlayers.add(new BoolSetting.Builder()
66
        .name("ignore-self")
67
        .description("Ignores yourself when tweaking player models.")
68
        .defaultValue(false)
69
        .visible(players::get)
70
        .build()
71
    );
72
73
    public final Setting<Boolean> playersTexture = sgPlayers.add(new BoolSetting.Builder()
74
        .name("texture")
75
        .description("Enables player model textures.")
76
        .defaultValue(false)
77
        .visible(players::get)
78
        .build()
79
    );
80
81
    public final Setting<SettingColor> playersColor = sgPlayers.add(new ColorSetting.Builder()
82
        .name("color")
83
        .description("The color of player models.")
84
        .defaultValue(new SettingColor(198, 135, 254, 150))
85
        .visible(players::get)
86
        .build()
87
    );
88
89
    public final Setting<Double> playersScale = sgPlayers.add(new DoubleSetting.Builder()
90
        .name("scale")
91
        .description("Players scale.")
92
        .defaultValue(1.0)
93
        .min(0.0)
94
        .visible(players::get)
95
        .build()
96
    );
97
98
    // Crystals
99
100
    public final Setting<Boolean> crystals = sgCrystals.add(new BoolSetting.Builder()
101
        .name("crystals")
102
        .description("Enables model tweaks for end crystals.")
103
        .defaultValue(false)
104
        .build()
105
    );
106
107
    public final Setting<Double> crystalsScale = sgCrystals.add(new DoubleSetting.Builder()
108
        .name("scale")
109
        .description("Crystal scale.")
110
        .defaultValue(0.6)
111
        .min(0)
112
        .visible(crystals::get)
113
        .build()
114
    );
115
116
    public final Setting<Double> crystalsBounce = sgCrystals.add(new DoubleSetting.Builder()
117
        .name("bounce")
118
        .description("How high crystals bounce.")
119
        .defaultValue(0.6)
120
        .min(0.0)
121
        .visible(crystals::get)
122
        .build()
123
    );
124
125
    public final Setting<Double> crystalsRotationSpeed = sgCrystals.add(new DoubleSetting.Builder()
126
        .name("rotation-speed")
127
        .description("Multiplies the rotation speed of the crystal.")
128
        .defaultValue(0.3)
129
        .min(0)
130
        .visible(crystals::get)
131
        .build()
132
    );
133
134
    public final Setting<Boolean> crystalsTexture = sgCrystals.add(new BoolSetting.Builder()
135
        .name("texture")
136
        .description("Whether to render crystal model textures.")
137
        .defaultValue(true)
138
        .visible(crystals::get)
139
        .build()
140
    );
141
142
    public final Setting<SettingColor> crystalsColor = sgCrystals.add(new ColorSetting.Builder()
143
        .name("crystal-color")
144
        .description("The color of the of the crystal.")
145
        .defaultValue(new SettingColor(198, 135, 254, 255))
146
        .visible(crystals::get)
147
        .build()
148
    );
149
150
    // Hand
151
152
    public final Setting<Boolean> hand = sgHand.add(new BoolSetting.Builder()
153
        .name("enabled")
154
        .description("Enables tweaks of hand rendering.")
155
        .defaultValue(false)
156
        .build()
157
    );
158
159
    public final Setting<Boolean> handTexture = sgHand.add(new BoolSetting.Builder()
160
        .name("texture")
161
        .description("Whether to render hand textures.")
162
        .defaultValue(false)
163
        .visible(hand::get)
164
        .build()
165
    );
166
167
    public final Setting<SettingColor> handColor = sgHand.add(new ColorSetting.Builder()
168
        .name("hand-color")
169
        .description("The color of your hand.")
170
        .defaultValue(new SettingColor(198, 135, 254, 150))
171
        .visible(hand::get)
172
        .build()
173
    );
174
175
    public static final Identifier BLANK = MeteorClient.identifier("textures/blank.png");
176
177
    public Chams() {
178
        super(Categories.Render, "chams", "Tweaks rendering of entities.");
179
    }
180
181
    public boolean shouldRender(Entity entity) {
182
        return isActive() && !isShader() && entities.get().contains(entity.getType()) && (entity != mc.player || !ignoreSelfDepth.get());
183
    }
184
185
    public boolean isShader() {
186
        return isActive() && shader.get() != Shader.None;
187
    }
188
189
    public enum Shader {
190
        Image,
191
        None
192
    }
193
}
194
MelaHack (ThunderHack fork)RENDERsrc/main/java/thunder/hack/features/modules/render/Chams.javaJava · 281 lines · 13.2 KB

Nice hand renders.

SettingsHandItemsHandItemsColorCrystalsCrystalColorStaticCrystalCrystalModePlayersPlayerColorFriendColorPlayerTextureSimpleAlternativeBlending
Chams.javaJava · Minecraft 26.2 · 281 lines · 13.2 KB · complete file, verbatimOriginal ↗
1
package thunder.hack.features.modules.render;
2
3
import com.mojang.blaze3d.vertex.BufferBuilder;
4
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
5
import com.mojang.blaze3d.vertex.PoseStack;
6
import thunder.hack.utility.render.Tesselator;
7
import com.mojang.blaze3d.vertex.VertexFormat;
8
import com.mojang.math.Axis;
9
import com.mojang.blaze3d.platform.GlStateManager;
10
import thunder.hack.utility.render.compat.RenderSystem;
11
import meteordevelopment.orbit.EventHandler;
12
import thunder.hack.utility.render.ShaderProgramKeys;
13
import net.minecraft.client.model.EntityModel;
14
import net.minecraft.client.model.object.crystal.EndCrystalModel;
15
import net.minecraft.client.player.AbstractClientPlayer;
16
import thunder.hack.utility.render.BufferRenderer;
17
import net.minecraft.client.renderer.SubmitNodeCollector;
18
import net.minecraft.client.renderer.entity.EntityRenderer;
19
import net.minecraft.client.renderer.entity.LivingEntityRenderer;
20
import net.minecraft.client.renderer.entity.state.EndCrystalRenderState;
21
import net.minecraft.client.renderer.entity.state.EntityRenderState;
22
import net.minecraft.client.renderer.entity.state.LivingEntityRenderState;
23
import net.minecraft.client.renderer.rendertype.RenderType;
24
import net.minecraft.client.renderer.rendertype.RenderTypes;
25
import net.minecraft.client.renderer.texture.OverlayTexture;
26
import net.minecraft.core.Direction;
27
import net.minecraft.resources.Identifier;
28
import net.minecraft.util.Mth;
29
import net.minecraft.world.entity.Entity;
30
import net.minecraft.world.entity.LivingEntity;
31
import net.minecraft.world.entity.Pose;
32
import net.minecraft.world.entity.player.Player;
33
import net.minecraft.world.phys.Vec3;
34
import org.joml.Quaternionf;
35
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
36
import thunder.hack.ThunderHack;
37
import thunder.hack.core.Managers;
38
import thunder.hack.events.impl.EventHeldItemRenderer;
39
import thunder.hack.features.modules.Module;
40
import thunder.hack.setting.Setting;
41
import thunder.hack.setting.impl.ColorSetting;
42
import thunder.hack.utility.render.Render2DEngine;
43
import thunder.hack.utility.render.TextureStorage;
44
45
import java.awt.*;
46
47
public class Chams extends Module {
48
    public Chams() {
49
        super("Chams", Category.RENDER);
50
    }
51
52
    public final Setting<Boolean> handItems = new Setting<>("HandItems", false);
53
    private final Setting<ColorSetting> handItemsColor = new Setting<>("HandItemsColor", new ColorSetting(new Color(0x9317DE5D, true)), v -> handItems.getValue());
54
55
    public final Setting<Boolean> crystals = new Setting<>("Crystals", false);
56
    private final Setting<ColorSetting> crystalColor = new Setting<>("CrystalColor", new ColorSetting(new Color(0x932DD8E8, true)), v -> crystals.getValue());
57
    private final Setting<Boolean> staticCrystal = new Setting<>("StaticCrystal", true, v -> crystals.getValue());
58
    private final Setting<CMode> crystalMode = new Setting<>("CrystalMode", CMode.One, v -> crystals.getValue());
59
60
    public final Setting<Boolean> players = new Setting<>("Players", false);
61
    private final Setting<ColorSetting> playerColor = new Setting<>("PlayerColor", new ColorSetting(new Color(0x932DD8E8, true)), v -> players.getValue());
62
    private final Setting<ColorSetting> friendColor = new Setting<>("FriendColor", new ColorSetting(new Color(0x932DE830, true)), v -> players.getValue());
63
    private final Setting<Boolean> playerTexture = new Setting<>("PlayerTexture", true, v -> players.getValue());
64
    private final Setting<Boolean> simple = new Setting<>("Simple", false, v -> players.getValue());
65
66
    private final Setting<Boolean> alternativeBlending = new Setting<>("AlternativeBlending", true);
67
68
    private enum CMode {
69
        One, Two, Three
70
    }
71
72
    private final Identifier crystalTexture = Identifier.parse("textures/entity/end_crystal/end_crystal.png");
73
    public void renderCrystal(EndCrystalRenderState state, PoseStack matrixStack, SubmitNodeCollector vertexConsumerProvider, int light, EndCrystalModel model) {
74
        RenderSystem.enableBlend();
75
        if (alternativeBlending.getValue())
76
            RenderSystem.blendFunc(GlStateManager.SrcFactor.SRC_ALPHA, GlStateManager.DstFactor.ONE);
77
        else RenderSystem.defaultBlendFunc();
78
        RenderSystem.disableCull();
79
        RenderSystem.disableDepthTest();
80
81
        RenderSystem.setShaderColor(crystalColor.getValue().getGlRed(), crystalColor.getValue().getGlGreen(), crystalColor.getValue().getGlBlue(), crystalColor.getValue().getGlAlpha());
82
        float originalAge = state.ageInTicks;
83
        if (staticCrystal.getValue()) {
84
            state.ageInTicks = 0.0f;
85
        }
86
87
        Identifier texture = crystalMode.getValue() == CMode.Two ? TextureStorage.crystalTexture2 : crystalTexture;
88
        RenderType layer = RenderTypes.entityCutout(texture);
89
90
        matrixStack.pushPose();
91
        matrixStack.scale(2.0f, 2.0f, 2.0f);
92
        matrixStack.translate(0.0f, -0.5f, 0.0f);
93
        model.setupAnim(state);
94
        vertexConsumerProvider.submitModel(model, state, matrixStack, layer, light, OverlayTexture.NO_OVERLAY, -1, null);
95
        matrixStack.popPose();
96
97
        state.ageInTicks = originalAge;
98
        RenderSystem.setShaderColor(1f, 1f, 1f, 1f);
99
        RenderSystem.disableBlend();
100
        RenderSystem.enableDepthTest();
101
        RenderSystem.enableCull();
102
    }
103
104
    public void renderPlayer(Player pe, float f, float g, PoseStack matrixStack, int i, EntityModel model, CallbackInfo ci, Runnable post) {
105
        RenderSystem.enableBlend();
106
        if (alternativeBlending.getValue())
107
            RenderSystem.blendFunc(GlStateManager.SrcFactor.SRC_ALPHA, GlStateManager.DstFactor.ONE);
108
        else RenderSystem.defaultBlendFunc();
109
        RenderSystem.enableCull();
110
        RenderSystem.disableDepthTest();
111
        BufferBuilder buffer;
112
113
        if (!simple.getValue()) {
114
            RenderSystem.setShaderTexture(0, ((AbstractClientPlayer) pe).getSkin().body().texturePath());
115
            RenderSystem.setShader(ShaderProgramKeys.POSITION_TEX);
116
            buffer = Tesselator.getInstance().begin(com.mojang.blaze3d.PrimitiveTopology.QUADS, DefaultVertexFormat.POSITION_TEX);
117
        } else {
118
            RenderSystem.setShader(ShaderProgramKeys.POSITION);
119
            buffer = Tesselator.getInstance().begin(com.mojang.blaze3d.PrimitiveTopology.QUADS, DefaultVertexFormat.POSITION);
120
        }
121
122
        float n;
123
        Direction direction;
124
        Entity entity;
125
        matrixStack.pushPose();
126
127
        if (Managers.FRIEND.isFriend(pe)) {
128
            RenderSystem.setShaderColor(friendColor.getValue().getGlRed(), friendColor.getValue().getGlGreen(), friendColor.getValue().getGlBlue(), friendColor.getValue().getGlAlpha());
129
        } else {
130
            RenderSystem.setShaderColor(playerColor.getValue().getGlRed(), playerColor.getValue().getGlGreen(), playerColor.getValue().getGlBlue(), playerColor.getValue().getGlAlpha());
131
        }
132
133
        float h = Mth.rotLerp(g, ((thunder.hack.injection.accesors.ILivingEntity) pe).getLastBodyYaw(), pe.yBodyRot);
134
        float j = Mth.rotLerp(g, ((thunder.hack.injection.accesors.ILivingEntity) pe).getLastHeadYaw(), pe.yHeadRot);
135
        float k = j - h;
136
        if (pe.isPassenger() && (entity = pe.getVehicle()) instanceof LivingEntity) {
137
            LivingEntity livingEntity2 = (LivingEntity) entity;
138
            h = Mth.rotLerp(g, ((thunder.hack.injection.accesors.ILivingEntity) livingEntity2).getLastBodyYaw(), livingEntity2.yBodyRot);
139
            k = j - h;
140
            float l = Mth.wrapDegrees(k);
141
            if (l < -85.0f) {
142
                l = -85.0f;
143
            }
144
            if (l >= 85.0f) {
145
                l = 85.0f;
146
            }
147
            h = j - l;
148
            if (l * l > 2500.0f) {
149
                h += l * 0.2f;
150
            }
151
            k = j - h;
152
        }
153
        float m = Mth.lerp(g, ((thunder.hack.injection.accesors.IEntity) pe).getLastPitch(), pe.getXRot());
154
        if (("Dinnerbone".equals(pe.getName().getString()) || "Grumm".equals(pe.getName().getString()))) {
155
            m *= -1.0f;
156
            k *= -1.0f;
157
        }
158
        if (pe.hasPose(Pose.SLEEPING) && (direction = pe.getBedOrientation()) != null) {
159
            n = pe.getEyeHeight(Pose.STANDING) - 0.1f;
160
            matrixStack.translate((float) (-direction.getStepX()) * n, 0.0f, (float) (-direction.getStepZ()) * n);
161
        }
162
        float l = pe.tickCount + g;
163
164
        setupTransforms1(pe, matrixStack, l, h, g);
165
        matrixStack.scale(-1.0f, -1.0f, 1.0f);
166
167
        matrixStack.scale(0.9375f, 0.9375f, 0.9375f);
168
        matrixStack.translate(0.0f, -1.501f, 0.0f);
169
170
        n = 0.0f;
171
        float o = 0.0f;
172
        if (!pe.isPassenger() && pe.isAlive()) {
173
            n = pe.walkAnimation.speed();
174
            o = pe.walkAnimation.position(g);
175
            if (pe.isBaby())
176
                o *= 3.0f;
177
178
            if (n > 1.0f)
179
                n = 1.0f;
180
        }
181
        LivingEntityRenderState renderState = null;
182
        EntityRenderer<? super Player, ? extends EntityRenderState> renderer = mc.getEntityRenderDispatcher().getRenderer(pe);
183
        EntityRenderState state = renderer.createRenderState(pe, g);
184
        if (state instanceof LivingEntityRenderState livingState) {
185
            renderState = livingState;
186
        }
187
        if (renderState != null) {
188
            @SuppressWarnings("unchecked")
189
            EntityModel<LivingEntityRenderState> typedModel = (EntityModel<LivingEntityRenderState>) model;
190
            typedModel.setupAnim(renderState);
191
            int p = LivingEntityRenderer.getOverlayCoords(renderState, 0);
192
            typedModel.renderToBuffer(matrixStack, buffer, i, p, -1);
193
        }
194
        Render2DEngine.endBuilding(buffer);
195
        RenderSystem.disableBlend();
196
        RenderSystem.disableCull();
197
        matrixStack.popPose();
198
        RenderSystem.setShaderColor(1f, 1f, 1f, 1f);
199
        RenderSystem.enableDepthTest();
200
        if (!playerTexture.getValue()) {
201
            ci.cancel();
202
            post.run();
203
        }
204
    }
205
206
    public void setupTransforms1(Player abstractClientPlayerEntity, PoseStack matrixStack, float f, float g, float h) {
207
        float j = abstractClientPlayerEntity.getSwimAmount(h);
208
        float k = abstractClientPlayerEntity.getViewXRot(h);
209
        float l;
210
        float m;
211
        if (abstractClientPlayerEntity.isFallFlying()) {
212
            setupTransforms(abstractClientPlayerEntity, matrixStack, f, g, h);
213
            l = abstractClientPlayerEntity.tickCount + h;
214
            m = Mth.clamp(l * l / 100.0F, 0.0F, 1.0F);
215
            if (!abstractClientPlayerEntity.isAutoSpinAttack()) {
216
                matrixStack.mulPose(Axis.XP.rotationDegrees(m * (-90.0F - k)));
217
            }
218
219
            Vec3 vec3d = abstractClientPlayerEntity.getViewVector(h);
220
            Vec3 vec3d2 = abstractClientPlayerEntity.getDeltaMovement();
221
            double d = vec3d2.horizontalDistanceSqr();
222
            double e = vec3d.horizontalDistanceSqr();
223
            if (d > 0.0 && e > 0.0) {
224
                double n = (vec3d2.x * vec3d.x + vec3d2.z * vec3d.z) / Math.sqrt(d * e);
225
                double o = vec3d2.x * vec3d.z - vec3d2.z * vec3d.x;
226
                matrixStack.mulPose(Axis.YP.rotation((float) (Math.signum(o) * Math.acos(n))));
227
            }
228
        } else if (j > 0.0F) {
229
            setupTransforms(abstractClientPlayerEntity, matrixStack, f, g, h);
230
            l = abstractClientPlayerEntity.isInWater() ? -90.0F - k : -90.0F;
231
            m = Mth.lerp(j, 0.0F, l);
232
            matrixStack.mulPose(Axis.XP.rotationDegrees(m));
233
            if (abstractClientPlayerEntity.isVisuallySwimming()) {
234
                matrixStack.translate(0.0F, -1.0F, 0.3F);
235
            }
236
        } else {
237
            setupTransforms(abstractClientPlayerEntity, matrixStack, f, g, h);
238
        }
239
    }
240
241
    private void setupTransforms(Player entity, PoseStack matrices, float animationProgress, float bodyYaw, float tickDelta) {
242
        if (!entity.hasPose(Pose.SLEEPING)) {
243
            matrices.mulPose(Axis.YP.rotationDegrees(180.0F - bodyYaw));
244
        }
245
246
        if (entity.deathTime > 0) {
247
            float f = ((float) entity.deathTime + tickDelta - 1.0F) / 20.0F * 1.6F;
248
            f = Mth.sqrt(f);
249
            if (f > 1.0F) {
250
                f = 1.0F;
251
            }
252
253
            matrices.mulPose(Axis.ZP.rotationDegrees(f * 90.0F));
254
        } else if (entity.isAutoSpinAttack()) {
255
            matrices.mulPose(Axis.XP.rotationDegrees(-90.0F - entity.getXRot()));
256
            matrices.mulPose(Axis.YP.rotationDegrees(((float) entity.tickCount + tickDelta) * -75.0F));
257
        } else if (entity.hasPose(Pose.SLEEPING)) {
258
            Direction direction = entity.getBedOrientation();
259
            float g = direction != null ? getYaw(direction) : bodyYaw;
260
            matrices.mulPose(Axis.YP.rotationDegrees(g));
261
            matrices.mulPose(Axis.ZP.rotationDegrees(90.0F));
262
            matrices.mulPose(Axis.YP.rotationDegrees(270.0F));
263
        }
264
    }
265
266
    private static float getYaw(Direction direction) {
267
        return switch (direction) {
268
            case NORTH -> 270.0f;
269
            case SOUTH -> 90.0f;
270
            case EAST -> 180.0f;
271
            default -> 0.0f;
272
        };
273
    }
274
275
    @EventHandler
276
    public void onRenderHands(EventHeldItemRenderer e) {
277
        if (handItems.getValue())
278
            RenderSystem.setShaderColor(handItemsColor.getValue().getRed() / 255f, handItemsColor.getValue().getGreen() / 255f, handItemsColor.getValue().getBlue() / 255f, handItemsColor.getValue().getAlpha() / 255f);
279
    }
280
}
281
OfflineClientRENDERsrc/main/java/com/jellypudding/offlineclient/modules/render/Chams.javaJava · 166 lines · 6.7 KB

Draws player and mob models through walls.

SettingsSelfThrough wallsColourOpacityFriend colourPlayer skinMob texturePlayer scaleCrystalsCrystal scaleCrystal bounceCrystal spinCrystal textureCrystal colourHandHand textureHand colourHand opacity
Chams.javaJava · Minecraft 26.2 · 166 lines · 6.7 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.render;
2
3
import com.jellypudding.offlineclient.module.Category;
4
import com.jellypudding.offlineclient.module.Module;
5
import com.jellypudding.offlineclient.setting.BoolSetting;
6
import com.jellypudding.offlineclient.setting.ColorSetting;
7
import com.jellypudding.offlineclient.setting.NumberSetting;
8
import com.jellypudding.offlineclient.util.ColorUtil;
9
import com.jellypudding.offlineclient.util.EntityFilter;
10
import com.jellypudding.offlineclient.util.EntityUtil;
11
import com.jellypudding.offlineclient.util.Modules;
12
import net.minecraft.resources.Identifier;
13
import net.minecraft.world.entity.Entity;
14
import net.minecraft.world.entity.LivingEntity;
15
import net.minecraft.world.entity.player.Player;
16
17
import java.util.List;
18
19
// EntityRendererMixin flags the target and LivingEntityRendererMixin swaps the
20
// render type. The crystal and avatar mixins reshape crystals and your own arm.
21
public final class Chams extends Module {
22
23
    // A plain white texture that leaves only the tint on a model.
24
    public static final Identifier BLANK = Identifier.parse("offlineclient:textures/blank.png");
25
26
    private static volatile Chams instance;
27
28
    private final EntityFilter filter = EntityFilter.living("Draw", "drawn", true,
29
        EntityFilter.Pick.NONE, List.of());
30
    private final BoolSetting self = new BoolSetting("Self",
31
        "Show your own body in third person.", false);
32
    private final BoolSetting throughWalls = new BoolSetting("Through walls",
33
        "Draw the model over blocks instead of only tinting it.", true);
34
    private final ColorSetting color = new ColorSetting("Colour",
35
        "Model colour.", 300, false);
36
    private final NumberSetting opacity = new NumberSetting("Opacity",
37
        "How solid the model looks.", 0.7, 0.1, 1, 0.05).min(0.05).max(1);
38
    private final BoolSetting friendColor = new BoolSetting("Friend colour",
39
        "Paint friends blue instead.", true);
40
    private final BoolSetting playerSkin = new BoolSetting("Player skin",
41
        "Keep the skin on players. Off paints them as one flat colour.", true);
42
    private final BoolSetting mobTexture = new BoolSetting("Mob texture",
43
        "Keep the texture on mobs. Off paints them as one flat colour.", true);
44
    private final NumberSetting playerScale = new NumberSetting("Player scale",
45
        "Makes player models bigger or smaller.", 1, 0.25, 3, 0.05, "x").min(0.05).max(10);
46
47
    private final BoolSetting crystals = new BoolSetting("Crystals",
48
        "Reshape and recolour end crystals.", false);
49
    private final NumberSetting crystalScale = new NumberSetting("Crystal scale",
50
        "How big a crystal is drawn.", 0.6, 0.1, 2, 0.05, "x").min(0.05).max(5)
51
        .under(crystals);
52
    private final NumberSetting crystalBounce = new NumberSetting("Crystal bounce",
53
        "How high a crystal bobs up and down.", 0.6, 0, 2, 0.05, "x").min(0).max(5)
54
        .under(crystals);
55
    private final NumberSetting crystalSpin = new NumberSetting("Crystal spin",
56
        "How fast a crystal turns.", 0.3, 0, 2, 0.05, "x").min(0).max(10)
57
        .under(crystals);
58
    private final BoolSetting crystalTexture = new BoolSetting("Crystal texture",
59
        "Keep the crystal texture under the colour. Off paints it flat.", true)
60
        .under(crystals);
61
    private final ColorSetting crystalColor = new ColorSetting("Crystal colour",
62
        "Colour tinted over a crystal.", 272, 0.47f, 1f, false)
63
        .under(crystals);
64
65
    private final BoolSetting hand = new BoolSetting("Hand",
66
        "Recolour your own arm in first person.", false);
67
    private final BoolSetting handTexture = new BoolSetting("Hand texture",
68
        "Keep your skin on the arm under the colour. Off paints it flat.", false)
69
        .under(hand);
70
    private final ColorSetting handColor = new ColorSetting("Hand colour",
71
        "Colour of the arm.", 272, 0.47f, 1f, false)
72
        .under(hand);
73
    private final NumberSetting handOpacity = new NumberSetting("Hand opacity",
74
        "How solid the arm looks.", 0.6, 0.1, 1, 0.05).min(0.05).max(1)
75
        .under(hand);
76
77
    public Chams() {
78
        super("Chams", "Draws player and mob models through walls.", Category.RENDER);
79
        addSettings(filter.settings());
80
        addSettings(self, throughWalls, color, opacity, friendColor, playerSkin, mobTexture, playerScale,
81
            crystals, crystalScale, crystalBounce, crystalSpin, crystalTexture, crystalColor,
82
            hand, handTexture, handColor, handOpacity);
83
        searchTags("see through", "models", "wallhack");
84
        instance = this;
85
    }
86
87
    // Null before the client has started.
88
    public static Chams get() {
89
        return instance;
90
    }
91
92
    public boolean applies(Entity entity) {
93
        if (!isEnabled() || !(entity instanceof LivingEntity living) || !living.isAlive()) {
94
            return false;
95
        }
96
        if (entity == mc.player) {
97
            return self.isOn() && showsSelf();
98
        }
99
        return filter.matches(entity);
100
    }
101
102
    // The player's own model is only on screen in third person or Freecam.
103
    private boolean showsSelf() {
104
        return Modules.enabled(Freecam.class) || !mc.options.getCameraType().isFirstPerson();
105
    }
106
107
    public boolean throughWalls() {
108
        return throughWalls.isOn();
109
    }
110
111
    // True when an entity loses its texture for a flat colour.
112
    public boolean flat(Entity entity) {
113
        return entity instanceof Player ? !playerSkin.isOn() : !mobTexture.isOn();
114
    }
115
116
    public int tintFor(Entity entity) {
117
        int base = color.getColor();
118
        if (friendColor.isOn() && entity instanceof Player player
119
            && EntityUtil.isFriend(player)) {
120
            base = EntityUtil.FRIEND_COLOR;
121
        }
122
        return ColorUtil.fade(base, opacity.getFloat());
123
    }
124
125
    // One for anything that is not a marked player.
126
    public float scaleFor(Entity entity) {
127
        return entity instanceof Player && applies(entity) ? playerScale.getFloat() : 1;
128
    }
129
130
    public boolean reshapesCrystals() {
131
        return isEnabled() && crystals.isOn();
132
    }
133
134
    public float crystalScale() {
135
        return crystalScale.getFloat();
136
    }
137
138
    public float crystalBounce() {
139
        return crystalBounce.getFloat();
140
    }
141
142
    public float crystalSpin() {
143
        return crystalSpin.getFloat();
144
    }
145
146
    public Identifier crystalTexture(Identifier vanilla) {
147
        return crystalTexture.isOn() ? vanilla : BLANK;
148
    }
149
150
    public int crystalColor() {
151
        return crystalColor.getColor();
152
    }
153
154
    public boolean paintsHand() {
155
        return isEnabled() && hand.isOn();
156
    }
157
158
    public Identifier handTexture(Identifier skin) {
159
        return handTexture.isOn() ? skin : BLANK;
160
    }
161
162
    public int handColor() {
163
        return ColorUtil.fade(handColor.getColor(), handOpacity.getFloat());
164
    }
165
}
166
CombatantVISUALSsrc/main/java/combatant/client/features/module/modules/visuals/Chams.javaJava · 1,233 lines · 56.5 KB
SettingshandChamsModechamsHandshandChamsFillColorhandChamsVisualColorSourcehandChamsMetallicBasehandChamsMetallicHighlighthandChamsEffectColorSourcehandChamsGlowColorhandChamsShadowColorhandChamsGlowhandChamsGlowAlphahandChamsGlowStrengthhandChamsShadowhandChamsShadowAlphahandChamsShadowStrengthhandChamsEdgeWidthhandChamsQualityhandChamsSmokeOctaveschamsSmokeSpeedhandChamsSmokeScalehandChamsSmokeContrasthandChamsSmokeSwirlhandChamsSmokeDensityhandChamsMetallicIntensityhandChamsMetallicSharpnesshandChamsMetallicEdgehandChamsMetallicSweepSpeedhandChamsMetallicSweepScalehandChamsMetallicBrushedLineshandChamsMetallicFlakeshandChamsMetallicPrismhandChamsGhostinghandChamsGhostingColorModehandChamsGhostingColorSpeedhandChamsGhostingColorhandChamsGhostingColor2handChamsGhostingStrengthhandChamsGhostingDurationhandChamsGhostingBlurhandChamsGhostingQuality
Chams.javaJava · Minecraft 26.2 · 1,233 lines · 56.5 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Combatant Client distribution.
3
 * Copyright (c) 2026 pivosos2007.
4
 *
5
 * Licensed under the GNU General Public License v3.0.
6
 */
7
8
package combatant.client.features.module.modules.visuals;
9
10
11
import combatant.client.features.theme.Theme;
12
import com.mojang.blaze3d.GpuFormat;
13
import com.mojang.blaze3d.pipeline.TextureTarget;
14
import com.mojang.blaze3d.systems.RenderSystem;
15
import com.mojang.blaze3d.textures.AddressMode;
16
import com.mojang.blaze3d.textures.FilterMode;
17
import com.mojang.blaze3d.textures.GpuSampler;
18
import com.mojang.blaze3d.textures.GpuTextureView;
19
import com.mojang.blaze3d.vertex.PoseStack;
20
import combatant.client.config.common.CommonSettingSchemas;
21
import combatant.client.config.values.*;
22
import net.irisshaders.iris.mixinterface.ItemInHandInterface;
23
import net.irisshaders.iris.pathways.HandRenderer;
24
import net.minecraft.client.Minecraft;
25
import net.minecraft.client.renderer.GameRenderer;
26
import net.minecraft.client.renderer.RenderBuffers;
27
import net.minecraft.client.renderer.SubmitNodeCollection;
28
import net.minecraft.client.renderer.SubmitNodeStorage;
29
import net.minecraft.client.renderer.feature.phase.FeatureRenderPhase;
30
import net.minecraft.client.renderer.feature.submit.SubmitNode;
31
import net.minecraft.client.renderer.feature.FeatureRenderDispatcher;
32
import net.minecraft.client.renderer.state.level.CameraRenderState;
33
import net.minecraft.util.Util;
34
import org.joml.Matrix4fc;
35
import combatant.client.features.theme.Themes;
36
import combatant.client.features.module.Module;
37
import combatant.client.features.module.ModuleCategory;
38
import combatant.client.features.module.ModuleInfo;
39
import combatant.client.features.module.Modules;
40
import combatant.client.mixins.accessors.GameRendererAccessor;
41
import combatant.client.mixins.iris.IrisHandRendererAccessor;
42
import combatant.client.render.engine.animation.AnimatedRenderColors;
43
import combatant.client.render.engine.pipeline.CombatantRenderPipelines;
44
import combatant.client.render.engine.postprocess.PostProcessManager;
45
import combatant.client.render.engine.postprocess.PostProcessPass;
46
import combatant.client.render.engine.postprocess.PostProcessExecutionContext;
47
import combatant.client.render.engine.postprocess.PostProcessBackendResourceOwner;
48
import combatant.client.render.engine.postprocess.HandChamsComputeBackend;
49
import combatant.client.features.gui.preview.VisualPreviewRuntime;
50
import combatant.client.render.engine.profiler.ProfilerPhase;
51
import combatant.client.render.engine.profiler.TracyGpuProfiler;
52
import combatant.client.render.engine.renderer.FullScreenRenderer;
53
import combatant.client.render.helpers.TickDelta;
54
import combatant.client.render.engine.uniform.impl.HandGhostingUniforms;
55
import combatant.client.render.engine.uniform.impl.HandGlassUniforms;
56
import combatant.client.render.engine.uniform.impl.HandMetallicUniforms;
57
import combatant.client.render.engine.uniform.impl.HandSmokeUniforms;
58
import combatant.client.render.iris.IrisHandMaskState;
59
import combatant.client.render.iris.IrisRuntime;
60
import combatant.client.render.engine.RenderState;
61
import combatant.client.render.engine.core.CombatantRenderSystem;
62
import combatant.client.render.engine.rhi.CombatantRhi;
63
64
//todo Description
65
@ModuleInfo(id = "chams", displayName = "Chams", category = ModuleCategory.VISUALS)
66
public class Chams extends Module {
67
68
    private static final int METALLIC_OCCUPANCY_CELL_SIZE = 8;
69
70
    private static final String SETTING_HANDS = "hands";
71
    private static final String SETTING_MODE = "mode";
72
    private static final String SETTING_FILL = "fill";
73
    private static final String SETTING_VISUAL_COLOR_SOURCE = "visual_color_source";
74
    private static final String SETTING_EFFECT_COLOR_SOURCE = "effect_color_source";
75
    private static final String SETTING_GLOW = "glow";
76
    private static final String SETTING_GLOW_COLOR = "glow_color";
77
    private static final String SETTING_GLOW_ALPHA = "glow_alpha";
78
    private static final String SETTING_GLOW_STRENGTH = "glow_strength";
79
    private static final String SETTING_SHADOW = "shadow";
80
    private static final String SETTING_SHADOW_COLOR = "shadow_color";
81
    private static final String SETTING_SHADOW_ALPHA = "shadow_alpha";
82
    private static final String SETTING_SHADOW_STRENGTH = "shadow_strength";
83
    private static final String SETTING_EDGE_WIDTH = "edge_width";
84
    private static final String SETTING_QUALITY = "quality";
85
    private static final String SETTING_SMOKE_OCTAVES = "smoke_octaves";
86
    private static final String SETTING_SMOKE_SPEED = "smoke_speed";
87
    private static final String SETTING_SMOKE_SCALE = "smoke_scale";
88
    private static final String SETTING_SMOKE_CONTRAST = "smoke_contrast";
89
    private static final String SETTING_SMOKE_SWIRL = "smoke_swirl";
90
    private static final String SETTING_SMOKE_DENSITY = "smoke_density";
91
    private static final String SETTING_METALLIC_BASE = "metallic_base";
92
    private static final String SETTING_METALLIC_HIGHLIGHT = "metallic_highlight";
93
    private static final String SETTING_METALLIC_INTENSITY = "metallic_intensity";
94
    private static final String SETTING_METALLIC_SHARPNESS = "metallic_sharpness";
95
    private static final String SETTING_METALLIC_EDGE = "metallic_edge";
96
    private static final String SETTING_METALLIC_SWEEP_SPEED = "metallic_sweep_speed";
97
    private static final String SETTING_METALLIC_SWEEP_SCALE = "metallic_sweep_scale";
98
    private static final String SETTING_METALLIC_BRUSHED_LINES = "metallic_brushed_lines";
99
    private static final String SETTING_METALLIC_FLAKES = "metallic_flakes";
100
    private static final String SETTING_METALLIC_PRISM = "metallic_prism";
101
    private static final String SETTING_GHOSTING = "ghosting";
102
    private static final String SETTING_GHOSTING_STRENGTH = "ghosting_strength";
103
    private static final String SETTING_GHOSTING_DURATION = "ghosting_duration";
104
    private static final String SETTING_GHOSTING_BLUR = "ghosting_blur";
105
    private static final String SETTING_GHOSTING_QUALITY = "ghosting_quality";
106
    private static final String SETTING_GHOSTING_OCTAVES = "ghosting_octaves";
107
    private static final String SETTING_GHOSTING_SPEED = "ghosting_speed";
108
    private static final String SETTING_GHOSTING_SCALE = "ghosting_scale";
109
    private static final String SETTING_GHOSTING_CONTRAST = "ghosting_contrast";
110
    private static final String SETTING_GHOSTING_SWIRL = "ghosting_swirl";
111
    private static final String SETTING_GHOSTING_DENSITY = "ghosting_density";
112
    private final Minecraft mc = Minecraft.getInstance();
113
    private final ModeValue mode =
114
            modeSetting("handChamsMode", SETTING_MODE, "Smoke", "Smoke", "Metallic", "Glass");
115
116
    private final BooleanValue hands =
117
            bool("chamsHands", SETTING_HANDS, true);
118
119
    private final RGBAColorValue fillColor =
120
            color("handChamsFillColor", SETTING_FILL, "#66FFFFFF");
121
122
    private final ModeValue visualColorSource =
123
            visibleWhen(modeSetting("handChamsVisualColorSource", SETTING_VISUAL_COLOR_SOURCE, "Custom", "Custom", "Theme"), this::isHandEffectMode);
124
    private final RGBColorValue metallicBase =
125
            visibleWhen(colorNoAlpha("handChamsMetallicBase", SETTING_METALLIC_BASE, "#B0B4BA"), this::isCustomMetallicVisualColor);
126
    private final RGBColorValue metallicHighlight =
127
            visibleWhen(colorNoAlpha("handChamsMetallicHighlight", SETTING_METALLIC_HIGHLIGHT, "#FFFFFF"), this::isCustomMetallicVisualColor);
128
    private final ModeValue effectColorSource =
129
            visibleWhen(modeSetting("handChamsEffectColorSource", SETTING_EFFECT_COLOR_SOURCE, "Theme", "Material", "Theme", "Custom"), this::isHandEffectMode);
130
    private final RGBColorValue glowColor =
131
            visibleWhen(colorNoAlpha("handChamsGlowColor", SETTING_GLOW_COLOR, "#87DFFF"), this::isCustomEffectColor);
132
    private final RGBColorValue shadowColor =
133
            visibleWhen(colorNoAlpha("handChamsShadowColor", SETTING_SHADOW_COLOR, "#10131A"), this::isCustomEffectColor);
134
    private final BooleanValue glow =
135
            visibleWhen(bool("handChamsGlow", SETTING_GLOW, true), this::isHandEffectMode);
136
    private final NumberValue<Float> glowAlpha =
137
            visibleWhen(num("handChamsGlowAlpha", SETTING_GLOW_ALPHA, 0.72f, 0.0f, 1.0f), this::isGlowVisible);
138
    private final NumberValue<Float> glowStrength =
139
            visibleWhen(num("handChamsGlowStrength", SETTING_GLOW_STRENGTH, 1.15f, 0.0f, 6.0f), this::isGlowVisible);
140
    private final BooleanValue shadow =
141
            visibleWhen(bool("handChamsShadow", SETTING_SHADOW, true), this::isHandEffectMode);
142
    private final NumberValue<Float> shadowAlpha =
143
            visibleWhen(num("handChamsShadowAlpha", SETTING_SHADOW_ALPHA, 0.48f, 0.0f, 1.0f), this::isShadowVisible);
144
    private final NumberValue<Float> shadowStrength =
145
            visibleWhen(num("handChamsShadowStrength", SETTING_SHADOW_STRENGTH, 1.0f, 0.0f, 4.0f), this::isShadowVisible);
146
    private final NumberValue<Float> edgeWidth =
147
            visibleWhen(num("handChamsEdgeWidth", SETTING_EDGE_WIDTH, 10.0f, 0.0f, 36.0f), this::isHandEffectMode);
148
    private final NumberValue<Integer> quality =
149
            visibleWhen(num("handChamsQuality", SETTING_QUALITY, 2, 1, 4), this::isHandEffectMode);
150
    private final NumberValue<Integer> smokeOctaves =
151
            visibleWhen(num("handChamsSmokeOctaves", SETTING_SMOKE_OCTAVES, 4, 1, 6), this::isSmokeMode);
152
    private final NumberValue<Float> smokeSpeed =
153
            visibleWhen(num("chamsSmokeSpeed", SETTING_SMOKE_SPEED, 0.72f, 0.0f, 3.0f), this::isSmokeMode);
154
    private final NumberValue<Float> smokeScale =
155
            visibleWhen(num("handChamsSmokeScale", SETTING_SMOKE_SCALE, 4.4f, 1.0f, 12.0f), this::isSmokeMode);
156
    private final NumberValue<Float> smokeContrast =
157
            visibleWhen(num("handChamsSmokeContrast", SETTING_SMOKE_CONTRAST, 1.12f, 0.35f, 2.4f), this::isSmokeMode);
158
    private final NumberValue<Float> smokeSwirl =
159
            visibleWhen(num("handChamsSmokeSwirl", SETTING_SMOKE_SWIRL, 0.85f, 0.0f, 2.5f), this::isSmokeMode);
160
    private final NumberValue<Float> smokeDensity =
161
            visibleWhen(num("handChamsSmokeDensity", SETTING_SMOKE_DENSITY, 1.0f, 0.2f, 2.5f), this::isSmokeMode);
162
    private final NumberValue<Float> metallicIntensity =
163
            visibleWhen(num("handChamsMetallicIntensity", SETTING_METALLIC_INTENSITY, 1.35f, 0.0f, 5.0f), this::isMetallicMode);
164
    private final NumberValue<Float> metallicSharpness =
165
            visibleWhen(num("handChamsMetallicSharpness", SETTING_METALLIC_SHARPNESS, 2.2f, 0.35f, 10.0f), this::isMetallicMode);
166
    private final NumberValue<Float> metallicEdge =
167
            visibleWhen(num("handChamsMetallicEdge", SETTING_METALLIC_EDGE, 1.25f, 0.0f, 4.0f), this::isMetallicMode);
168
    private final NumberValue<Float> metallicSweepSpeed =
169
            visibleWhen(num("handChamsMetallicSweepSpeed", SETTING_METALLIC_SWEEP_SPEED, 1.15f, 0.0f, 5.0f), this::isMetallicMode);
170
    private final NumberValue<Float> metallicSweepScale =
171
            visibleWhen(num("handChamsMetallicSweepScale", SETTING_METALLIC_SWEEP_SCALE, 10.0f, 1.0f, 36.0f), this::isMetallicMode);
172
    private final NumberValue<Float> metallicBrushedLines =
173
            visibleWhen(num("handChamsMetallicBrushedLines", SETTING_METALLIC_BRUSHED_LINES, 0.55f, 0.0f, 1.0f), this::isMetallicMode);
174
    private final NumberValue<Float> metallicFlakes =
175
            visibleWhen(num("handChamsMetallicFlakes", SETTING_METALLIC_FLAKES, 0.25f, 0.0f, 1.0f), this::isMetallicMode);
176
    private final NumberValue<Float> metallicPrism =
177
            visibleWhen(num("handChamsMetallicPrism", SETTING_METALLIC_PRISM, 0.18f, 0.0f, 1.0f), this::isMetallicMode);
178
179
    private final BooleanValue ghosting =
180
            bool("handChamsGhosting", SETTING_GHOSTING, false);
181
    private final EnumValue<AnimatedRenderColors.Mode> ghostingColorMode = visibleWhen(
182
            common(enumSetting(
183
                    "handChamsGhostingColorMode",
184
                    "ghosting_color_mode",
185
                    AnimatedRenderColors.Mode.STATIC,
186
                    AnimatedRenderColors.Mode.STATIC,
187
                    AnimatedRenderColors.Mode.RAINBOW,
188
                    AnimatedRenderColors.Mode.LIGHT_RAINBOW,
189
                    AnimatedRenderColors.Mode.SKY,
190
                    AnimatedRenderColors.Mode.FADE,
191
                    AnimatedRenderColors.Mode.DOUBLE_COLOR,
192
                    AnimatedRenderColors.Mode.ANALOGOUS,
193
                    AnimatedRenderColors.Mode.THEME
194
            ), CommonSettingSchemas.RENDER_COLOR_MODE.commonI18nKey()),
195
            this::isGhostingVisible
196
    );
197
    private final NumberValue<Integer> ghostingColorSpeed = visibleWhen(
198
            common(num("handChamsGhostingColorSpeed", "ghosting_color_speed", 18, 2, 54),
199
                    CommonSettingSchemas.RENDER_COLOR_SPEED.commonI18nKey()),
200
            () -> isGhostingVisible() && AnimatedRenderColors.animated(ghostingColorMode.get())
201
    );
202
    private final RGBAColorValue ghostingColor = visibleWhen(
203
            common(color("handChamsGhostingColor", "ghosting_color", "#B05CFFE6"),
204
                    CommonSettingSchemas.RENDER_PRIMARY_COLOR.commonI18nKey()),
205
            this::isGhostingVisible
206
    );
207
    private final RGBAColorValue ghostingColor2 = visibleWhen(
208
            common(color("handChamsGhostingColor2", "ghosting_color_2", "#A04D8CFF"),
209
                    CommonSettingSchemas.RENDER_SECONDARY_COLOR.commonI18nKey()),
210
            () -> isGhostingVisible() && AnimatedRenderColors.usesSecondary(ghostingColorMode.get())
211
    );
212
    private final NumberValue<Float> ghostingStrength = visibleWhen(
213
            num("handChamsGhostingStrength", SETTING_GHOSTING_STRENGTH, 1.0f, 0.0f, 3.0f),
214
            this::isGhostingVisible
215
    );
216
    private final NumberValue<Float> ghostingDuration = visibleWhen(
217
            num("handChamsGhostingDuration", SETTING_GHOSTING_DURATION, 0.28f, 0.05f, 1.25f),
218
            this::isGhostingVisible
219
    );
220
    private final NumberValue<Float> ghostingBlur = visibleWhen(
221
            num("handChamsGhostingBlur", SETTING_GHOSTING_BLUR, 3.0f, 0.0f, 12.0f),
222
            this::isGhostingVisible
223
    );
224
    private final ModeValue ghostingQuality = visibleWhen(
225
            modeSetting("handChamsGhostingQuality", SETTING_GHOSTING_QUALITY, "Balanced",
226
                    "Performance", "Balanced", "High", "Ultra"),
227
            this::isGhostingVisible
228
    );
229
    private final NumberValue<Integer> ghostingOctaves = visibleWhen(
230
            num("handChamsGhostingOctaves", SETTING_GHOSTING_OCTAVES, 3, 1, 6),
231
            this::isGhostingVisible
232
    );
233
    private final NumberValue<Float> ghostingSpeed = visibleWhen(
234
            num("handChamsGhostingSpeed", SETTING_GHOSTING_SPEED, 0.65f, 0.0f, 3.0f),
235
            this::isGhostingVisible
236
    );
237
    private final NumberValue<Float> ghostingScale = visibleWhen(
238
            num("handChamsGhostingScale", SETTING_GHOSTING_SCALE, 3.4f, 0.5f, 12.0f),
239
            this::isGhostingVisible
240
    );
241
    private final NumberValue<Float> ghostingContrast = visibleWhen(
242
            num("handChamsGhostingContrast", SETTING_GHOSTING_CONTRAST, 1.1f, 0.35f, 2.4f),
243
            this::isGhostingVisible
244
    );
245
    private final NumberValue<Float> ghostingSwirl = visibleWhen(
246
            num("handChamsGhostingSwirl", SETTING_GHOSTING_SWIRL, 0.8f, 0.0f, 3.0f),
247
            this::isGhostingVisible
248
    );
249
    private final NumberValue<Float> ghostingDensity = visibleWhen(
250
            num("handChamsGhostingDensity", SETTING_GHOSTING_DENSITY, 1.0f, 0.2f, 2.5f),
251
            this::isGhostingVisible
252
    );
253
254
    private final HandChamsComputeBackend chamsCompute = new HandChamsComputeBackend();
255
    private final PostProcessPass handsPass = new HandsPass();
256
    private final PostProcessPass ghostingPass = new GhostingPass();
257
    private TextureTarget handMask;
258
    private TextureTarget metallicOccupancyRaw;
259
    private TextureTarget metallicOccupancyDilated;
260
    private GpuSampler handMaskSampler;
261
    private TextureTarget ghostHistoryRead;
262
    private TextureTarget ghostHistoryWrite;
263
    private int bufferW = -1;
264
    private int bufferH = -1;
265
    private int metallicOccupancyW = -1;
266
    private int metallicOccupancyH = -1;
267
    private int ghostBufferW = -1;
268
    private int ghostBufferH = -1;
269
    private boolean maskReady;
270
    private boolean ghostMaskReady;
271
    private boolean ghostHistoryNeedsClear = true;
272
    private boolean ghostComputeNeedsReset = true;
273
    private RenderBuffers handMaskRenderBuffers;
274
    private FeatureRenderDispatcher handMaskFeatureDispatcher;
275
    private final java.util.ArrayList<SubmitNode> handSnapshotScratch = new java.util.ArrayList<>(32);
276
277
    {
278
        PostProcessManager.register(handsPass);
279
        PostProcessManager.register(ghostingPass);
280
    }
281
282
    private static float channel(int argb, int shift) {
283
        return ((argb >> shift) & 0xFF) / 255.0f;
284
    }
285
286
    private static float clamp01(float v) {
287
        if (v < 0.0f) return 0.0f;
288
        if (v > 1.0f) return 1.0f;
289
        return v;
290
    }
291
292
    private static int forceOpaque(int argb) {
293
        return 0xFF000000 | (argb & 0x00FFFFFF);
294
    }
295
296
    private static int mixRgb(int a, int b, float t) {
297
        t = clamp01(t);
298
        int ar = (a >>> 16) & 0xFF;
299
        int ag = (a >>> 8) & 0xFF;
300
        int ab = a & 0xFF;
301
        int br = (b >>> 16) & 0xFF;
302
        int bg = (b >>> 8) & 0xFF;
303
        int bb = b & 0xFF;
304
        int rr = Math.round(ar + (br - ar) * t);
305
        int rg = Math.round(ag + (bg - ag) * t);
306
        int rb = Math.round(ab + (bb - ab) * t);
307
        return 0xFF000000 | (rr << 16) | (rg << 8) | rb;
308
    }
309
310
    public boolean isActive() {
311
        return isEnabled() && mc.player != null && mc.level != null;
312
    }
313
314
    @Override
315
    public void onDisable() {
316
        maskReady = false;
317
        ghostMaskReady = false;
318
        ghostHistoryNeedsClear = true;
319
        ghostComputeNeedsReset = true;
320
        chamsCompute.close();
321
        closeMetallicOccupancyBuffers();
322
        closeStandaloneHandRenderer();
323
    }
324
325
    @Override
326
    public void onTick() {
327
        // Do not carry a stale temporal silhouette across modes where no first-person hand mask
328
        // is being produced. Buffers are cleared lazily when Ghosting becomes active again.
329
        if (!hands.get() || !ghosting.get() || !isFirstPersonHandContext()) {
330
            ghostMaskReady = false;
331
            ghostHistoryNeedsClear = true;
332
            ghostComputeNeedsReset = true;
333
            chamsCompute.invalidateGhostHistory();
334
        }
335
    }
336
337
    private FeatureRenderDispatcher getStandaloneHandFeatureDispatcher() {
338
        if (handMaskFeatureDispatcher != null) {
339
            return handMaskFeatureDispatcher;
340
        }
341
        if (mc.gameRenderer == null || mc.getModelManager() == null || mc.getAtlasManager() == null || mc.font == null) {
342
            return null;
343
        }
344
        handMaskRenderBuffers = new RenderBuffers(1);
345
        handMaskFeatureDispatcher = new FeatureRenderDispatcher(
346
                handMaskRenderBuffers,
347
                mc.getModelManager(),
348
                mc.getAtlasManager(),
349
                mc.font,
350
                mc.gameRenderer.gameRenderState()
351
        );
352
        return handMaskFeatureDispatcher;
353
    }
354
355
    private void endStandaloneHandFrame() {
356
        if (handMaskRenderBuffers != null) {
357
            handMaskRenderBuffers.endFrame();
358
        }
359
    }
360
361
    private void closeStandaloneHandRenderer() {
362
        if (handMaskFeatureDispatcher != null) {
363
            handMaskFeatureDispatcher.close();
364
            handMaskFeatureDispatcher = null;
365
        }
366
        if (handMaskRenderBuffers != null) {
367
            handMaskRenderBuffers.close();
368
            handMaskRenderBuffers = null;
369
        }
370
    }
371
372
    public boolean renderHandMask(GameRenderer renderer, CameraRenderState cameraRenderState, float tickDelta, Matrix4fc positionMatrix) {
373
        if (!isActiveForHandRender() || mc.player == null || mc.level == null) return false;
374
        if (mc.gameMode == null) return false;
375
        if (!hands.get() || !shouldRenderHand()) return false;
376
        if (!isFirstPersonHandContext()) return false;
377
378
        maskReady = false;
379
        ensureBuffers();
380
        if (handMask == null) return false;
381
382
        if (mc.gameRenderer.mainRenderTarget() == null) return false;
383
384
        var colorTex = handMask.getColorTexture();
385
        if (colorTex == null) return false;
386
387
        var encoder = RenderSystem.getDevice().createCommandEncoder();
388
        encoder.clearColorTexture(colorTex, new org.joml.Vector4f(0.0f, 0.0f, 0.0f, 0.0f));
389
390
        var depthTex = handMask.getDepthTexture();
391
        if (depthTex != null) {
392
            encoder.clearDepthTexture(depthTex, 0.0);
393
        }
394
395
        GpuTextureView prevColor = RenderSystem.outputColorTextureOverride;
396
        GpuTextureView prevDepth = RenderSystem.outputDepthTextureOverride;
397
        boolean prevRendering3D = RenderState.rendering3D;
398
399
        RenderSystem.outputColorTextureOverride = handMask.getColorTextureView();
400
        RenderSystem.outputDepthTextureOverride = handMask.getDepthTextureView();
401
        RenderState.rendering3D = true;
402
403
        ViewModel viewModel = Modules.get(ViewModel.class);
404
        boolean hmiReplay = viewModel != null && viewModel.beginHmiReplayPass();
405
        try (TracyGpuProfiler.Scope ignoredGpu = TracyGpuProfiler.beginZone("3d:chams_hand_mask")) {
406
            ((GameRendererAccessor) renderer).invokeRenderHand(cameraRenderState, tickDelta, positionMatrix);
407
        } finally {
408
            if (hmiReplay) viewModel.endHmiReplayPass();
409
            RenderState.rendering3D = prevRendering3D;
410
            RenderSystem.outputColorTextureOverride = prevColor;
411
            RenderSystem.outputDepthTextureOverride = prevDepth;
412
        }
413
414
        markHandMaskReady();
415
        return true;
416
    }
417
418
    public SubmitNodeStorage snapshotPreparedHandScene(SubmitNodeStorage storage) {
419
        // renderAllFeatures() consumes/clears its SubmitNodeStorage in 26.2. Chams must never feed
420
        // Minecraft's live hand storage into the auxiliary mask dispatcher, otherwise the real
421
        // vanilla hand pass that follows has no submits left to draw.
422
        if (IrisRuntime.isShaderpackRendererActive() && !VisualPreviewRuntime.isRenderingSubject()) return null;
423
        if (!isActiveForHandRender() || mc.player == null || mc.level == null) return null;
424
        if (storage == null || !hands.get() || !shouldRenderHand()) return null;
425
        if (!isFirstPersonHandContext()) return null;
426
427
        try (ProfilerPhase.Scope ignored = ProfilerPhase.scope("chams:hand_snapshot")) {
428
            SubmitNodeStorage snapshot = new SubmitNodeStorage();
429
            for (var entry : storage.getSubmitsPerOrder().int2ObjectEntrySet()) {
430
                SubmitNodeCollection sourceCollection = entry.getValue();
431
                SubmitNodeCollection targetCollection = snapshot.order(entry.getIntKey());
432
433
                var sourcePhases = sourceCollection.allPhases();
434
                var targetPhases = targetCollection.allPhases();
435
                if (sourcePhases.size() != targetPhases.size()) {
436
                    // A mod injected a phase asymmetrically. Do not risk consuming/corrupting the live
437
                    // hand storage; simply skip Chams for this frame.
438
                    return null;
439
                }
440
441
                for (int i = 0; i < sourcePhases.size(); i++) {
442
                    FeatureRenderPhase<?> source = sourcePhases.get(i);
443
                    if (!source.isEmpty()) copyPhase(source, targetPhases.get(i));
444
                }
445
            }
446
            return snapshot;
447
        }
448
    }
449
450
    @SuppressWarnings({"rawtypes", "unchecked"})
451
    private void copyPhase(FeatureRenderPhase<?> source, FeatureRenderPhase<?> target) {
452
        // FeatureRenderPhase.sortInto() is destructive in 26.2: both the simple and translucent
453
        // implementations clear their backing submits after forwarding them to Output. A naive
454
        // "copy" therefore emptied Minecraft's live hand storage before the vanilla dispatcher
455
        // could draw it, leaving only the Chams post-process fill visible.
456
        //
457
        // Drain once into a temporary list, then restore the exact SubmitNode objects back into the
458
        // source phase and also submit them to the isolated mask phase. Re-submission preserves the
459
        // phase's own batching / translucent distance bookkeeping without sharing mutable phase
460
        // containers between the vanilla scene and the auxiliary mask renderer.
461
        handSnapshotScratch.clear();
462
        source.sortInto((submit, strictlyOrdered) -> handSnapshotScratch.add(submit));
463
464
        FeatureRenderPhase rawSource = source;
465
        FeatureRenderPhase rawTarget = target;
466
        for (SubmitNode submit : handSnapshotScratch) {
467
            rawSource.submit(submit);
468
            rawTarget.submit(submit);
469
        }
470
        handSnapshotScratch.clear();
471
    }
472
473
    public boolean renderPreparedHandScene(SubmitNodeStorage storage) {
474
        // The storage passed here is an isolated snapshot. Minecraft's original hand storage has
475
        // already been rendered to the scene by the vanilla dispatcher before this method runs.
476
        if (IrisRuntime.isShaderpackRendererActive() && !VisualPreviewRuntime.isRenderingSubject()) return false;
477
        if (!isActiveForHandRender() || mc.player == null || mc.level == null) return false;
478
        if (storage == null) return false;
479
        if (!hands.get() || !shouldRenderHand()) return false;
480
        if (!isFirstPersonHandContext()) return false;
481
482
        maskReady = false;
483
        ensureBuffers();
484
        if (handMask == null || handMask.getColorTexture() == null) return false;
485
486
        var encoder = RenderSystem.getDevice().createCommandEncoder();
487
        encoder.clearColorTexture(handMask.getColorTexture(), new org.joml.Vector4f(0.0f, 0.0f, 0.0f, 0.0f));
488
        if (handMask.getDepthTexture() != null) {
489
            encoder.clearDepthTexture(handMask.getDepthTexture(), 0.0);
490
        }
491
492
        FeatureRenderDispatcher maskDispatcher = getStandaloneHandFeatureDispatcher();
493
        if (maskDispatcher == null) return false;
494
495
        GpuTextureView prevColor = RenderSystem.outputColorTextureOverride;
496
        GpuTextureView prevDepth = RenderSystem.outputDepthTextureOverride;
497
        boolean prevRendering3D = RenderState.rendering3D;
498
        RenderSystem.outputColorTextureOverride = handMask.getColorTextureView();
499
        RenderSystem.outputDepthTextureOverride = handMask.getDepthTextureView();
500
        RenderState.rendering3D = true;
501
        try {
502
            try (ProfilerPhase.Scope ignored = ProfilerPhase.scope("chams:hand_mask_render");
503
                 TracyGpuProfiler.Scope ignoredGpu = TracyGpuProfiler.beginZone("3d:chams_hand_mask")) {
504
                maskDispatcher.renderAllFeatures(storage);
505
            }
506
            markHandMaskReady();
507
        } finally {
508
            endStandaloneHandFrame();
509
            RenderState.rendering3D = prevRendering3D;
510
            RenderSystem.outputColorTextureOverride = prevColor;
511
            RenderSystem.outputDepthTextureOverride = prevDepth;
512
        }
513
514
        return true;
515
    }
516
517
    public boolean renderIrisHandMask(GameRenderer renderer,
518
                                      CameraRenderState cameraRenderState,
519
                                      Matrix4fc positionMatrix,
520
                                      float tickDelta) {
521
        if (!IrisRuntime.isShaderpackRendererActive() || !isActiveForHandRender() || mc.player == null || mc.level == null) {
522
            return false;
523
        }
524
        if (!hands.get() || !shouldRenderHand() || !isFirstPersonHandContext()) {
525
            return false;
526
        }
527
        if (renderer == null || cameraRenderState == null || positionMatrix == null) {
528
            return false;
529
        }
530
531
        FeatureRenderDispatcher dispatcher = getStandaloneHandFeatureDispatcher();
532
        if (dispatcher == null) {
533
            return false;
534
        }
535
536
        maskReady = false;
537
        ensureBuffers();
538
        if (handMask == null || handMask.getColorTexture() == null) {
539
            return false;
540
        }
541
542
        var encoder = RenderSystem.getDevice().createCommandEncoder();
543
        encoder.clearColorTexture(handMask.getColorTexture(), new org.joml.Vector4f(0.0f, 0.0f, 0.0f, 0.0f));
544
        if (handMask.getDepthTexture() != null) {
545
            encoder.clearDepthTexture(handMask.getDepthTexture(), 0.0);
546
        }
547
548
        GpuTextureView prevColor = RenderSystem.outputColorTextureOverride;
549
        GpuTextureView prevDepth = RenderSystem.outputDepthTextureOverride;
550
        boolean prevRendering3D = RenderState.rendering3D;
551
        RenderSystem.outputColorTextureOverride = handMask.getColorTextureView();
552
        RenderSystem.outputDepthTextureOverride = handMask.getDepthTextureView();
553
        RenderState.rendering3D = true;
554
        RenderSystem.backupProjectionMatrix();
555
        ViewModel viewModel = Modules.get(ViewModel.class);
556
        boolean hmiReplay = viewModel != null && viewModel.beginHmiReplayPass();
557
        try (TracyGpuProfiler.Scope ignoredGpu = TracyGpuProfiler.beginZone("3d:chams_hand_mask")) {
558
            renderIrisHandMaskPhase(renderer, cameraRenderState, positionMatrix, dispatcher, tickDelta, true);
559
            renderIrisHandMaskPhase(renderer, cameraRenderState, positionMatrix, dispatcher, tickDelta, false);
560
        } finally {
561
            if (hmiReplay) viewModel.endHmiReplayPass();
562
            ((IrisHandRendererAccessor) HandRenderer.INSTANCE).combatant$setRenderingSolid(false);
563
            RenderSystem.restoreProjectionMatrix();
564
            RenderState.rendering3D = prevRendering3D;
565
            RenderSystem.outputColorTextureOverride = prevColor;
566
            RenderSystem.outputDepthTextureOverride = prevDepth;
567
        }
568
569
        markHandMaskReady();
570
        return true;
571
    }
572
573
    private void renderIrisHandMaskPhase(GameRenderer renderer,
574
                                          CameraRenderState cameraRenderState,
575
                                          Matrix4fc positionMatrix,
576
                                          FeatureRenderDispatcher dispatcher,
577
                                          float tickDelta,
578
                                          boolean solidPhase) {
579
        IrisHandRendererAccessor irisHand = (IrisHandRendererAccessor) HandRenderer.INSTANCE;
580
        irisHand.combatant$setRenderingSolid(solidPhase);
581
582
        PoseStack handMatrices = irisHand.combatant$invokeSetupGlState(renderer, cameraRenderState, positionMatrix, tickDelta);
583
        handMatrices.pushPose();
584
        var modelView = RenderSystem.getModelViewStack();
585
        modelView.pushMatrix();
586
        modelView.set(handMatrices.last().pose());
587
588
        SubmitNodeStorage handSubmits = new SubmitNodeStorage();
589
        IrisHandMaskState.renderBothPhases(() ->
590
                ((ItemInHandInterface) renderer.itemInHandRenderer).iris$renderHandsWithCustomRenderer(
591
                        HandRenderer.INSTANCE,
592
                        tickDelta,
593
                        new PoseStack(),
594
                        handSubmits,
595
                        mc.player,
596
                        mc.getEntityRenderDispatcher().getPackedLightCoords(mc.player, tickDelta)
597
                )
598
        );
599
        try {
600
            dispatcher.renderAllFeatures(handSubmits);
601
        } finally {
602
            modelView.popMatrix();
603
            handMatrices.popPose();
604
            endStandaloneHandFrame();
605
        }
606
    }
607
608
    private boolean shouldRenderHand() {
609
        if (VisualPreviewRuntime.isRenderingSubject()) return true;
610
        Freecam fc = Modules.get(Freecam.class);
611
        return fc == null || !fc.isEnabled() || fc.renderHand();
612
    }
613
614
    private boolean isActiveForHandRender() {
615
        return isEnabled() || VisualPreviewRuntime.isPreviewingModule("chams");
616
    }
617
618
    private boolean isFirstPersonHandContext() {
619
        return VisualPreviewRuntime.isRenderingSubject() || mc.options.getCameraType().isFirstPerson();
620
    }
621
622
    /** Composites only Chams' hand material and trail passes for an isolated preview scene. */
623
    public void compositePreparedHandScene(float tickDelta) {
624
        PostProcessManager.renderSelected(PostProcessPass.Phase.POST_HAND, tickDelta,
625
                pass -> pass == handsPass || pass == ghostingPass);
626
    }
627
628
    private void markHandMaskReady() {
629
        maskReady = true;
630
        if (ghosting.get()) {
631
            ghostMaskReady = true;
632
        } else {
633
            ghostMaskReady = false;
634
            // A later toggle must never resurrect an old trail. Clear lazily on the next ghost pass.
635
            ghostHistoryNeedsClear = true;
636
            ghostComputeNeedsReset = true;
637
            chamsCompute.invalidateGhostHistory();
638
        }
639
    }
640
641
    private void ensureBuffers() {
642
        int w = mc.getWindow().getWidth();
643
        int h = mc.getWindow().getHeight();
644
        if (w <= 0 || h <= 0) return;
645
646
        if (handMask == null) {
647
            handMask = new TextureTarget("combatant-hand-mask", w, h, true, GpuFormat.RGBA8_UNORM);
648
            bufferW = w;
649
            bufferH = h;
650
        } else if (w != bufferW || h != bufferH) {
651
            handMask.resize(w, h);
652
            bufferW = w;
653
            bufferH = h;
654
        }
655
    }
656
657
    private boolean ensureGhostBuffers() {
658
        int w = mc.getWindow().getWidth();
659
        int h = mc.getWindow().getHeight();
660
        if (w <= 0 || h <= 0) return false;
661
662
        // Quality controls both temporal-buffer resolution and shader sample count. Keeping the
663
        // history independent from the full-resolution hand mask makes the expensive temporal
664
        // stages scale predictably without changing the actual hand render resolution.
665
        float historyScale = ghostHistoryScale();
666
        int historyW = Math.max(1, Math.round(w * historyScale));
667
        int historyH = Math.max(1, Math.round(h * historyScale));
668
669
        if (ghostHistoryRead == null || ghostHistoryWrite == null) {
670
            ghostHistoryRead = new TextureTarget("combatant-hand-ghost-history-a", historyW, historyH, false, GpuFormat.RGBA8_UNORM);
671
            ghostHistoryWrite = new TextureTarget("combatant-hand-ghost-history-b", historyW, historyH, false, GpuFormat.RGBA8_UNORM);
672
            ghostBufferW = historyW;
673
            ghostBufferH = historyH;
674
            ghostHistoryNeedsClear = true;
675
        } else if (historyW != ghostBufferW || historyH != ghostBufferH) {
676
            ghostHistoryRead.resize(historyW, historyH);
677
            ghostHistoryWrite.resize(historyW, historyH);
678
            ghostBufferW = historyW;
679
            ghostBufferH = historyH;
680
            ghostHistoryNeedsClear = true;
681
        }
682
683
        if (ghostHistoryNeedsClear) {
684
            var encoder = RenderSystem.getDevice().createCommandEncoder();
685
            if (ghostHistoryRead.getColorTexture() != null) {
686
                encoder.clearColorTexture(ghostHistoryRead.getColorTexture(), new org.joml.Vector4f(0.0f, 0.0f, 0.0f, 0.0f));
687
            }
688
            if (ghostHistoryWrite.getColorTexture() != null) {
689
                encoder.clearColorTexture(ghostHistoryWrite.getColorTexture(), new org.joml.Vector4f(0.0f, 0.0f, 0.0f, 0.0f));
690
            }
691
            ghostHistoryNeedsClear = false;
692
        }
693
694
        return ghostHistoryRead.getColorTextureView() != null && ghostHistoryWrite.getColorTextureView() != null;
695
    }
696
697
    private boolean ensureMetallicOccupancyBuffers() {
698
        int framebufferW = mc.getWindow().getWidth();
699
        int framebufferH = mc.getWindow().getHeight();
700
        if (framebufferW <= 0 || framebufferH <= 0) return false;
701
702
        int occupancyW = Math.max(1, (framebufferW + METALLIC_OCCUPANCY_CELL_SIZE - 1) / METALLIC_OCCUPANCY_CELL_SIZE);
703
        int occupancyH = Math.max(1, (framebufferH + METALLIC_OCCUPANCY_CELL_SIZE - 1) / METALLIC_OCCUPANCY_CELL_SIZE);
704
        try {
705
            if (metallicOccupancyRaw == null || metallicOccupancyDilated == null) {
706
                closeMetallicOccupancyBuffers();
707
                metallicOccupancyRaw = new TextureTarget(
708
                        "combatant-hand-metallic-occupancy-raw", occupancyW, occupancyH, false, GpuFormat.RGBA8_UNORM);
709
                metallicOccupancyDilated = new TextureTarget(
710
                        "combatant-hand-metallic-occupancy-dilated", occupancyW, occupancyH, false, GpuFormat.RGBA8_UNORM);
711
                metallicOccupancyW = occupancyW;
712
                metallicOccupancyH = occupancyH;
713
            } else if (occupancyW != metallicOccupancyW || occupancyH != metallicOccupancyH) {
714
                metallicOccupancyRaw.resize(occupancyW, occupancyH);
715
                metallicOccupancyDilated.resize(occupancyW, occupancyH);
716
                metallicOccupancyW = occupancyW;
717
                metallicOccupancyH = occupancyH;
718
            }
719
            return metallicOccupancyRaw.getColorTextureView() != null
720
                    && metallicOccupancyDilated.getColorTextureView() != null;
721
        } catch (Throwable ignored) {
722
            closeMetallicOccupancyBuffers();
723
            return false;
724
        }
725
    }
726
727
    private void closeMetallicOccupancyBuffers() {
728
        if (metallicOccupancyRaw != null) {
729
            metallicOccupancyRaw.destroyBuffers();
730
            metallicOccupancyRaw = null;
731
        }
732
        if (metallicOccupancyDilated != null) {
733
            metallicOccupancyDilated.destroyBuffers();
734
            metallicOccupancyDilated = null;
735
        }
736
        metallicOccupancyW = -1;
737
        metallicOccupancyH = -1;
738
    }
739
740
    private void swapGhostHistory() {
741
        TextureTarget tmp = ghostHistoryRead;
742
        ghostHistoryRead = ghostHistoryWrite;
743
        ghostHistoryWrite = tmp;
744
    }
745
746
    private GpuSampler getHandMaskSampler() {
747
        if (handMaskSampler == null) {
748
            handMaskSampler = RenderSystem.getSamplerCache().getSampler(
749
                    AddressMode.CLAMP_TO_EDGE,
750
                    AddressMode.CLAMP_TO_EDGE,
751
                    FilterMode.NEAREST,
752
                    FilterMode.NEAREST,
753
                    false
754
            );
755
        }
756
        return handMaskSampler;
757
    }
758
759
    private boolean isSmokeMode() {
760
        return "Smoke".equals(mode.get());
761
    }
762
763
    private boolean isMetallicMode() {
764
        return "Metallic".equals(mode.get());
765
    }
766
767
    private boolean isHandEffectMode() {
768
        return isSmokeMode() || isMetallicMode();
769
    }
770
771
    private boolean isGlowVisible() {
772
        return isHandEffectMode() && glow.get();
773
    }
774
775
    private boolean isShadowVisible() {
776
        return isHandEffectMode() && shadow.get();
777
    }
778
779
    private boolean isCustomEffectColor() {
780
        return isHandEffectMode() && "Custom".equals(effectColorSource.get());
781
    }
782
783
    private boolean isCustomMetallicVisualColor() {
784
        return isMetallicMode() && "Custom".equals(visualColorSource.get());
785
    }
786
787
    public boolean isGlassMode() {
788
        return "Glass".equals(mode.get());
789
    }
790
791
    private boolean isGhostingVisible() {
792
        return hands.get() && ghosting.get();
793
    }
794
795
    private int ghostQualityLevel() {
796
        return switch (ghostingQuality.get()) {
797
            case "Performance" -> 1;
798
            case "High" -> 3;
799
            case "Ultra" -> 4;
800
            default -> 2;
801
        };
802
    }
803
804
    private float ghostHistoryScale() {
805
        return switch (ghostQualityLevel()) {
806
            case 1 -> 0.35f;
807
            case 3 -> 0.75f;
808
            case 4 -> 1.0f;
809
            default -> 0.50f;
810
        };
811
    }
812
813
    private int materialFillRgb() {
814
        int fill = fillColor.getArgb();
815
        if ("Theme".equals(visualColorSource.get())) {
816
            Themes.Theme theme = Theme.theme();
817
            return forceOpaque(mixRgb(theme.accent(), theme.textPrimary(), 0.18f));
818
        }
819
        return forceOpaque(fill);
820
    }
821
822
    private int metallicBaseRgb() {
823
        if ("Theme".equals(visualColorSource.get())) {
824
            Themes.Theme theme = Theme.theme();
825
            return forceOpaque(mixRgb(theme.surfaceHover(), theme.accent(), 0.42f));
826
        }
827
        return forceOpaque(metallicBase.getArgb());
828
    }
829
830
    private int metallicHighlightRgb() {
831
        if ("Theme".equals(visualColorSource.get())) {
832
            Themes.Theme theme = Theme.theme();
833
            return forceOpaque(mixRgb(theme.textPrimary(), theme.accentSoft(), 0.28f));
834
        }
835
        return forceOpaque(metallicHighlight.getArgb());
836
    }
837
838
    private int glowRgb(int materialRgb) {
839
        String source = effectColorSource.get();
840
        if ("Custom".equals(source)) return forceOpaque(glowColor.getArgb());
841
        if ("Theme".equals(source)) return forceOpaque(Theme.theme().accentSoft());
842
        return forceOpaque(mixRgb(materialRgb, 0xFFFFFFFF, 0.25f));
843
    }
844
845
    private int shadowRgb(int materialRgb) {
846
        String source = effectColorSource.get();
847
        if ("Custom".equals(source)) return forceOpaque(shadowColor.getArgb());
848
        if ("Theme".equals(source))
849
            return forceOpaque(mixRgb(Theme.theme().windowBg(), Theme.theme().accent(), 0.08f));
850
        return forceOpaque(mixRgb(materialRgb, 0xFF05070C, 0.72f));
851
    }
852
853
    private boolean renderHands(GpuTextureView src, GpuTextureView dst, float tickDelta) {
854
        if (!maskReady) return false;
855
        if (handMask == null) {
856
            maskReady = false;
857
            return false;
858
        }
859
860
        var maskView = handMask.getColorTextureView();
861
        if (maskView == null) {
862
            maskReady = false;
863
            return false;
864
        }
865
866
        float rawTime = getRawTime();
867
868
        if ("Glass".equals(mode.get())) {
869
            int fillArgb = fillColor.getArgb();
870
871
            float fillR = channel(fillArgb, 16);
872
            float fillG = channel(fillArgb, 8);
873
            float fillB = channel(fillArgb, 0);
874
            float fillA = channel(fillArgb, 24);
875
876
            int w = mc.getWindow().getWidth();
877
            int h = mc.getWindow().getHeight();
878
            float glassAlpha = clamp01(fillA);
879
            float glassStrength = Math.max(0.0f, fillA * 4.0f);
880
            float glassLevel = Math.min(glassStrength, 4.0f);
881
882
            // Hand glass is intentionally blur-first, like Renderer2D liquid glass.
883
            // The item is already rendered in src; this pass only adds frosted refraction on top.
884
            float edgeWidth = 12.0f + glassLevel * 2.25f;
885
            float refractionPx = 5.5f + glassLevel * 2.35f;
886
            float hazeStrength = 0.72f + Math.min(glassStrength, 3.0f) * 0.085f;
887
            float frostBlurPx = 5.0f + glassLevel * 1.65f;
888
            float bodyFrost = 0.48f + Math.min(glassStrength, 3.0f) * 0.105f;
889
            float chromaticPx = 1.65f + glassLevel * 0.42f;
890
            float edgeRefractionMul = 1.15f + glassLevel * 0.11f;
891
            float clarity = 0.08f;
892
893
            HandGlassUniforms.update(
894
                    w, h, rawTime, edgeWidth,
895
                    fillR, fillG, fillB, glassAlpha,
896
                    glassStrength, refractionPx, hazeStrength, frostBlurPx,
897
                    bodyFrost, chromaticPx, edgeRefractionMul, clarity
898
            );
899
900
            try (TracyGpuProfiler.Scope ignoredGpu = TracyGpuProfiler.beginZone("3d:chams:hands_glass")) {
901
                FullScreenRenderer.begin("Combatant Hand Glass")
902
                        .attachment(dst)
903
                        .pipeline(CombatantRenderPipelines.HAND_GLASS)
904
                        .uniform("HandGlass", HandGlassUniforms.get())
905
                        .sampler("u_Src", src, PostProcessManager.getSampler())
906
                        .sampler("u_Mask", maskView, getHandMaskSampler())
907
                        .end();
908
            }
909
        } else if ("Metallic".equals(mode.get())) {
910
            int fillArgb = fillColor.getArgb();
911
            int baseRgb = metallicBaseRgb();
912
            int hiRgb = metallicHighlightRgb();
913
            int glowRgb = glowRgb(baseRgb);
914
            int shadowRgb = shadowRgb(baseRgb);
915
916
            float fillA = channel(fillArgb, 24);
917
            float glowA = glow.get() ? glowAlpha.get() : 0.0f;
918
            float shadowA = shadow.get() ? shadowAlpha.get() : 0.0f;
919
            GpuTextureView occupancyView = chamsCompute.buildMetallicOccupancy(
920
                    CombatantRenderSystem.rhi(),
921
                    maskView,
922
                    getHandMaskSampler(),
923
                    mc.getWindow().getWidth(),
924
                    mc.getWindow().getHeight(),
925
                    edgeWidth.get(),
926
                    METALLIC_OCCUPANCY_CELL_SIZE
927
            );
928
            boolean computeOccupancyReady = occupancyView != null;
929
            boolean occupancyReady = computeOccupancyReady || ensureMetallicOccupancyBuffers();
930
931
            HandMetallicUniforms.update(
932
                    channel(baseRgb, 16), channel(baseRgb, 8), channel(baseRgb, 0), fillA,
933
                    channel(hiRgb, 16), channel(hiRgb, 8), channel(hiRgb, 0), 1.0f,
934
                    channel(glowRgb, 16), channel(glowRgb, 8), channel(glowRgb, 0), glowA,
935
                    channel(shadowRgb, 16), channel(shadowRgb, 8), channel(shadowRgb, 0), shadowA,
936
                    metallicIntensity.get(), metallicSharpness.get(), metallicEdge.get(), rawTime,
937
                    metallicSweepSpeed.get(), metallicSweepScale.get(), metallicBrushedLines.get(), metallicFlakes.get(),
938
                    glowStrength.get(), shadowStrength.get(), edgeWidth.get(), metallicPrism.get(),
939
                    occupancyReady
940
            );
941
942
            try (TracyGpuProfiler.Scope ignoredGpu = TracyGpuProfiler.beginZone("3d:chams:hands_metallic")) {
943
                if (!computeOccupancyReady) {
944
                    occupancyView = maskView;
945
                    if (occupancyReady) {
946
                        try (TracyGpuProfiler.Scope ignoredOccupancy = TracyGpuProfiler.beginZone("3d:chams:metallic_occupancy")) {
947
                            FullScreenRenderer.begin("Combatant Hand Metallic Occupancy")
948
                                    .attachment(metallicOccupancyRaw)
949
                                    .pipeline(CombatantRenderPipelines.HAND_MASK_OCCUPANCY)
950
                                    .sampler("u_Mask", maskView, getHandMaskSampler())
951
                                    .end();
952
                            FullScreenRenderer.begin("Combatant Hand Metallic Occupancy Dilate")
953
                                    .attachment(metallicOccupancyDilated)
954
                                    .pipeline(CombatantRenderPipelines.HAND_MASK_OCCUPANCY_DILATE)
955
                                    .uniform("HandMetallic", HandMetallicUniforms.get())
956
                                    .sampler("u_Mask", metallicOccupancyRaw.getColorTextureView(), getHandMaskSampler())
957
                                    .end();
958
                            occupancyView = metallicOccupancyDilated.getColorTextureView();
959
                        }
960
                    }
961
                }
962
                try (TracyGpuProfiler.Scope ignoredMaterial = TracyGpuProfiler.beginZone("3d:chams:metallic_material")) {
963
                    FullScreenRenderer.begin("Combatant Hand Metallic")
964
                            .attachment(dst)
965
                            .pipeline(CombatantRenderPipelines.HAND_METALLIC)
966
                            .uniform("HandMetallic", HandMetallicUniforms.get())
967
                            .sampler("u_Src", src, PostProcessManager.getSampler())
968
                            .sampler("u_Mask", maskView, getHandMaskSampler())
969
                            .sampler("u_Occupancy", occupancyView, getHandMaskSampler())
970
                            .end();
971
                }
972
            }
973
        } else {
974
            int fillArgb = fillColor.getArgb();
975
            int fillRgb = materialFillRgb();
976
            int glowRgb = glowRgb(fillRgb);
977
            int shadowRgb = shadowRgb(fillRgb);
978
979
            float fillA = channel(fillArgb, 24);
980
            float glowA = glow.get() ? glowAlpha.get() : 0.0f;
981
            float shadowA = shadow.get() ? shadowAlpha.get() : 0.0f;
982
983
            int w = mc.getWindow().getWidth();
984
            int h = mc.getWindow().getHeight();
985
986
            HandSmokeUniforms.update(
987
                    channel(fillRgb, 16), channel(fillRgb, 8), channel(fillRgb, 0), fillA,
988
                    channel(glowRgb, 16), channel(glowRgb, 8), channel(glowRgb, 0), glowA,
989
                    channel(shadowRgb, 16), channel(shadowRgb, 8), channel(shadowRgb, 0), shadowA,
990
                    edgeWidth.get(), quality.get(), smokeOctaves.get(), rawTime * smokeSpeed.get(),
991
                    w, h, smokeScale.get(), smokeContrast.get(),
992
                    smokeSwirl.get(), glowStrength.get(), shadowStrength.get(), smokeDensity.get()
993
            );
994
995
            try (TracyGpuProfiler.Scope ignoredGpu = TracyGpuProfiler.beginZone("3d:chams:hands_smoke")) {
996
                FullScreenRenderer.begin("Combatant Hand Smoke")
997
                        .attachment(dst)
998
                        .pipeline(CombatantRenderPipelines.HAND_SMOKE)
999
                        .uniform("HandSmoke", HandSmokeUniforms.get())
1000
                        .sampler("u_Src", src, PostProcessManager.getSampler())
1001
                        .sampler("u_Mask", maskView, getHandMaskSampler())
1002
                        .end();
1003
            }
1004
        }
1005
1006
        maskReady = false;
1007
        return true;
1008
    }
1009
1010
    private boolean renderGhosting(PostProcessExecutionContext execution) {
1011
        if (execution == null || execution.source() == null || execution.destination() == null) return false;
1012
        GpuTextureView maskView = readyGhostMask();
1013
        if (maskView == null) return false;
1014
1015
        GhostFrameParams frame = ghostFrameParams();
1016
        if (execution.destinationStorage() != null && chamsCompute.supported(execution.rhi())) {
1017
            boolean computed = chamsCompute.renderGhosting(
1018
                    execution.rhi(),
1019
                    execution.destinationStorage(),
1020
                    execution.source(),
1021
                    maskView,
1022
                    PostProcessManager.getSampler(),
1023
                    mc.getWindow().getWidth(),
1024
                    mc.getWindow().getHeight(),
1025
                    frame.dt(),
1026
                    frame.time(),
1027
                    frame.colorR(),
1028
                    frame.colorG(),
1029
                    frame.colorB(),
1030
                    frame.colorA(),
1031
                    frame.decay(),
1032
                    frame.strength(),
1033
                    frame.blurPx(),
1034
                    0.96f,
1035
                    frame.quality(),
1036
                    frame.octaves(),
1037
                    frame.speed(),
1038
                    frame.scale(),
1039
                    frame.swirl(),
1040
                    frame.contrast(),
1041
                    frame.density(),
1042
                    frame.historyScale(),
1043
                    ghostComputeNeedsReset
1044
            );
1045
            if (computed) {
1046
                ghostComputeNeedsReset = false;
1047
                // Raster history is a separate fallback chain. Keep it marked stale while compute owns history.
1048
                ghostHistoryNeedsClear = true;
1049
                ghostMaskReady = false;
1050
                return true;
1051
            }
1052
        }
1053
1054
        // A policy/backend change back to compute must never resurrect an old compute trail.
1055
        ghostComputeNeedsReset = true;
1056
        chamsCompute.invalidateGhostHistory();
1057
        return renderGhostingRaster(execution.source(), execution.destination(), maskView, frame);
1058
    }
1059
1060
1061
    private GpuTextureView readyGhostMask() {
1062
        if (!ghostMaskReady || handMask == null || handMask.getColorTextureView() == null) {
1063
            ghostMaskReady = false;
1064
            return null;
1065
        }
1066
        return handMask.getColorTextureView();
1067
    }
1068
1069
    private GhostFrameParams ghostFrameParams() {
1070
        float dt = TickDelta.frameDeltaSeconds();
1071
        if (!Float.isFinite(dt) || dt <= 0.0f) dt = 1.0f / 60.0f;
1072
        dt = Math.min(dt, 0.10f);
1073
1074
        float duration = Math.max(0.01f, ghostingDuration.get());
1075
        float decay = (float) Math.pow(0.02, dt / duration);
1076
        int ghostArgb = AnimatedRenderColors.resolve(
1077
                ghostingColorMode.get(),
1078
                ghostingColorSpeed.get(),
1079
                0,
1080
                ghostingColor.getArgb(),
1081
                ghostingColor2.getArgb(),
1082
                true
1083
        );
1084
        return new GhostFrameParams(
1085
                dt, getRawTime(),
1086
                channel(ghostArgb, 16), channel(ghostArgb, 8), channel(ghostArgb, 0), channel(ghostArgb, 24),
1087
                decay, ghostingStrength.get(), ghostingBlur.get(),
1088
                ghostQualityLevel(), ghostingOctaves.get(), ghostingSpeed.get(), ghostingScale.get(),
1089
                ghostingSwirl.get(), ghostingContrast.get(), ghostingDensity.get(), ghostHistoryScale()
1090
        );
1091
    }
1092
1093
    private boolean renderGhostingRaster(GpuTextureView src,
1094
                                         GpuTextureView dst,
1095
                                         GpuTextureView maskView,
1096
                                         GhostFrameParams frame) {
1097
        if (!ensureGhostBuffers()) {
1098
            ghostMaskReady = false;
1099
            return false;
1100
        }
1101
1102
        GpuTextureView historyView = ghostHistoryRead.getColorTextureView();
1103
        GpuTextureView nextHistoryView = ghostHistoryWrite.getColorTextureView();
1104
        if (historyView == null || nextHistoryView == null) {
1105
            ghostMaskReady = false;
1106
            return false;
1107
        }
1108
1109
        HandGhostingUniforms.update(
1110
                mc.getWindow().getWidth(),
1111
                mc.getWindow().getHeight(),
1112
                frame.dt(),
1113
                frame.time(),
1114
                frame.colorR(), frame.colorG(), frame.colorB(), frame.colorA(),
1115
                frame.decay(),
1116
                frame.strength(),
1117
                frame.blurPx(),
1118
                0.96f,
1119
                frame.quality(),
1120
                frame.octaves(),
1121
                frame.speed(),
1122
                frame.scale(),
1123
                frame.swirl(),
1124
                frame.contrast(),
1125
                frame.density(),
1126
                frame.historyScale()
1127
        );
1128
1129
        try (TracyGpuProfiler.Scope ignoredGpu = TracyGpuProfiler.beginZone("3d:chams:ghost_history")) {
1130
            FullScreenRenderer.begin("Combatant Hand Ghost History")
1131
                    .attachment(nextHistoryView)
1132
                    .pipeline(CombatantRenderPipelines.HAND_GHOSTING_HISTORY)
1133
                    .uniform("HandGhosting", HandGhostingUniforms.get())
1134
                    .sampler("u_History", historyView, PostProcessManager.getSampler())
1135
                    .sampler("u_Mask", maskView, PostProcessManager.getSampler())
1136
                    .end();
1137
        }
1138
1139
        try (TracyGpuProfiler.Scope ignoredGpu = TracyGpuProfiler.beginZone("3d:chams:ghost_composite")) {
1140
            FullScreenRenderer.begin("Combatant Hand Ghost Composite")
1141
                    .attachment(dst)
1142
                    .pipeline(CombatantRenderPipelines.HAND_GHOSTING)
1143
                    .uniform("HandGhosting", HandGhostingUniforms.get())
1144
                    .sampler("u_Src", src, PostProcessManager.getSampler())
1145
                    .sampler("u_History", nextHistoryView, PostProcessManager.getSampler())
1146
                    .end();
1147
        }
1148
1149
        swapGhostHistory();
1150
        ghostComputeNeedsReset = true;
1151
        ghostMaskReady = false;
1152
        return true;
1153
    }
1154
1155
    private record GhostFrameParams(
1156
            float dt, float time,
1157
            float colorR, float colorG, float colorB, float colorA,
1158
            float decay, float strength, float blurPx,
1159
            int quality, int octaves, float speed, float scale,
1160
            float swirl, float contrast, float density, float historyScale
1161
    ) { }
1162
1163
    private float getRawTime() {
1164
        return (float) (Util.getMillis() / 1000.0);
1165
    }
1166
1167
    private final class HandsPass implements PostProcessPass, PostProcessBackendResourceOwner {
1168
        @Override
1169
        public boolean isActive() {
1170
            return isActiveForHandRender()
1171
                    && mc.player != null
1172
                    && mc.level != null
1173
                    && hands.get()
1174
                    && isFirstPersonHandContext();
1175
        }
1176
1177
        @Override
1178
        public Phase getPhase() {
1179
            return Phase.POST_HAND;
1180
        }
1181
1182
        @Override
1183
        public boolean render(PostProcessExecutionContext execution) {
1184
            if (execution == null || execution.context() == null) return false;
1185
            if (!isActiveForHandRender() || mc.player == null || mc.level == null) return false;
1186
            if (!hands.get() || !isFirstPersonHandContext()) return false;
1187
            return Chams.this.renderHands(
1188
                    execution.source(), execution.destination(), execution.context().tickDelta());
1189
        }
1190
1191
        @Override
1192
        public void releaseBackendResources(CombatantRhi owner) {
1193
            chamsCompute.release(owner);
1194
        }
1195
    }
1196
1197
    private final class GhostingPass implements PostProcessPass {
1198
        @Override
1199
        public boolean isActive() {
1200
            return isActiveForHandRender()
1201
                    && mc.player != null
1202
                    && mc.level != null
1203
                    && hands.get()
1204
                    && ghosting.get()
1205
                    && isFirstPersonHandContext();
1206
        }
1207
1208
        @Override
1209
        public int getPriority() {
1210
            // Must run after HandsPass so the trail is composited over Smoke/Metallic/Glass.
1211
            return 20;
1212
        }
1213
1214
        @Override
1215
        public Phase getPhase() {
1216
            return Phase.POST_HAND;
1217
        }
1218
1219
        @Override
1220
        public boolean prefersStorageOutput(CombatantRhi rhi) {
1221
            return chamsCompute.supported(rhi);
1222
        }
1223
1224
        @Override
1225
        public boolean render(PostProcessExecutionContext execution) {
1226
            if (!isActive()) return false;
1227
            return Chams.this.renderGhosting(execution);
1228
        }
1229
1230
    }
1231
1232
}
1233
LiquidBounce (Kotlin)RENDERsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/render/ModuleChams.ktKotlin · 302 lines · 12.0 KB

Renders player's through walls.

SettingsFileFilteringOffsetTileWidth
ModuleChams.ktKotlin · Minecraft 26.2 · 302 lines · 12.0 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
3
 *
4
 * Copyright (c) 2015 - 2026 CCBlueX
5
 *
6
 * LiquidBounce is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * LiquidBounce is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
18
 */
19
package net.ccbluex.liquidbounce.features.module.modules.render
20
21
import com.mojang.blaze3d.pipeline.BlendFunction
22
import com.mojang.blaze3d.pipeline.ColorTargetState
23
import com.mojang.blaze3d.pipeline.RenderPipeline
24
import com.mojang.blaze3d.pipeline.RenderTarget
25
import com.mojang.blaze3d.systems.RenderSystem
26
import com.mojang.blaze3d.textures.FilterMode
27
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet
28
import net.ccbluex.liquidbounce.LiquidBounce
29
import net.ccbluex.liquidbounce.annotations.ValueClassCandidate
30
import net.ccbluex.liquidbounce.config.types.list.Tagged
31
import net.ccbluex.liquidbounce.config.types.group.Mode
32
import net.ccbluex.liquidbounce.config.types.group.ModeValueGroup
33
import net.ccbluex.liquidbounce.config.types.toTextureProperty
34
import net.ccbluex.liquidbounce.features.module.ClientModule
35
import net.ccbluex.liquidbounce.features.module.ModuleCategories
36
import net.ccbluex.liquidbounce.injection.mixins.minecraft.render.MixinRenderTypeAccessor
37
import net.ccbluex.liquidbounce.render.ClientRenderPipelines
38
import net.ccbluex.liquidbounce.render.ClientRenderPipelines.screenQuadSnippet
39
import net.ccbluex.liquidbounce.render.ClientUniformDefine
40
import net.ccbluex.liquidbounce.render.buffers.CachedUniform
41
import net.ccbluex.liquidbounce.render.createRenderPass
42
import net.ccbluex.liquidbounce.render.engine.LazyRenderTargetHolder
43
import net.ccbluex.liquidbounce.render.withOutputTarget
44
import net.ccbluex.liquidbounce.utils.combat.shouldBeShown
45
import net.ccbluex.liquidbounce.utils.io.PNG_AND_JPG
46
import net.ccbluex.liquidbounce.utils.kotlin.optional
47
import net.minecraft.client.renderer.BindGroupLayouts
48
import net.minecraft.client.renderer.feature.ItemFeatureRenderer
49
import net.minecraft.client.renderer.rendertype.OutputTarget
50
import net.minecraft.client.renderer.rendertype.RenderType
51
import net.minecraft.util.Util
52
import net.minecraft.world.entity.Entity
53
import org.joml.Vector2f
54
import java.util.function.Function
55
56
object ModuleChams : ClientModule("Chams", ModuleCategories.RENDER) {
57
58
    private val modes = choices("Mode", Normal, arrayOf(Normal, Image))
59
60
    private val supportedRenderTypes: Set<String> = hashSetOf(
61
        "armor_cutout_no_cull",
62
        "armor_decal_cutout_no_cull",
63
        "armor_entity_glint",
64
        "entity_translucent",
65
        "entity_cutout",
66
        "entity_cutout_cull",
67
        "entity_cutout_no_cull",
68
        "entity_solid",
69
        "entity_glint",
70
        "glint",
71
        "glint_translucent",
72
        "item_cutout",
73
        "item_translucent"
74
    )
75
76
    private val renderTargetHolder = LazyRenderTargetHolder(this.name, useDepth = true)
77
    private val blitSampler = RenderSystem.getSamplerCache().getClampToEdge(FilterMode.NEAREST)
78
    private val outputTarget = OutputTarget("liquidbounce_chams", renderTargetHolder)
79
80
    @ValueClassCandidate
81
    @JvmRecord
82
    private data class ImageUniform(
83
        val scaleX: Float,
84
        val scaleY: Float,
85
        val offsetX: Float = 0f,
86
        val offsetY: Float = 0f,
87
    )
88
89
    private val pipelineBlit: RenderPipeline =
90
        ClientRenderPipelines.newPipeline("chams/blit") {
91
            screenQuadSnippet()
92
            withFragmentShader("core/blit_screen")
93
            withBindGroupLayout(BindGroupLayouts.IN_SAMPLER)
94
            withColorTargetState(ColorTargetState(BlendFunction.TRANSLUCENT))
95
            withDepthStencilState(optional())
96
        }
97
98
    private val remapRenderType: Function<RenderType, RenderType> =
99
        Util.memoize { original ->
100
            val renderTypeAccessor = original as MixinRenderTypeAccessor
101
102
            RenderType.create(
103
                "liquidbounce_chams/${renderTypeAccessor.name}",
104
                renderTypeAccessor.state.withOutputTarget(outputTarget),
105
            )
106
        }
107
108
    private val heldItemEntityContext = ScopedValue.newInstance<Entity>()
109
    private val heldItemSubmits = ReferenceOpenHashSet<ItemFeatureRenderer.Submit>()
110
111
    private var dirty = false
112
113
    private fun supports(renderType: RenderType): Boolean =
114
        supportedRenderTypes.contains((renderType as MixinRenderTypeAccessor).name)
115
116
    /** Remaps an entity render type to the chams target when applicable. */
117
    fun remapIfNeeded(renderType: RenderType, entity: Entity?): RenderType {
118
        if (!running || !entity.shouldBeShown() || !supports(renderType)) {
119
            return renderType
120
        }
121
122
        dirty = true
123
        return remapRenderType.apply(renderType)
124
    }
125
126
    /** Runs a third-person held-item submission with the current entity bound. */
127
    fun withHeldItemContext(entity: Entity?, block: Runnable) {
128
        if (running && entity.shouldBeShown()) {
129
            ScopedValue.where(heldItemEntityContext, entity).run(block)
130
        } else {
131
            block.run()
132
        }
133
    }
134
135
    /** Marks an item submit as coming from the current held-item context. */
136
    fun markHeldItemSubmitIfActive(submit: ItemFeatureRenderer.Submit) {
137
        if (!heldItemEntityContext.isBound) {
138
            return
139
        }
140
141
        heldItemSubmits.add(submit)
142
    }
143
144
    /** Returns whether the submit was created from a held-item context. */
145
    fun isHeldItemSubmit(submit: ItemFeatureRenderer.Submit): Boolean =
146
        heldItemSubmits.contains(submit)
147
148
    /** Remaps a deferred held-item render type to the chams target when applicable. */
149
    fun remapHeldItemRenderTypeIfNeeded(submit: ItemFeatureRenderer.Submit, renderType: RenderType): RenderType {
150
        if (!isHeldItemSubmit(submit) || !supports(renderType)) {
151
            return renderType
152
        }
153
154
        dirty = true
155
        return remapRenderType.apply(renderType)
156
    }
157
158
    /** Remaps an immediate held-item render type using the current scoped entity. */
159
    fun remapCurrentHeldItemRenderTypeIfNeeded(renderType: RenderType): RenderType {
160
        val entity = if (heldItemEntityContext.isBound) heldItemEntityContext.get() else return renderType
161
        return remapIfNeeded(renderType, entity)
162
    }
163
164
    /** Ensures the chams target exists before any remapped draws in this frame. */
165
    fun beginFrameIfNeeded() {
166
        if (!running || !dirty) {
167
            return
168
        }
169
170
        renderTargetHolder.initAndGet()
171
    }
172
173
    /** Blits the accumulated chams target into the main render target. */
174
    fun compositeIfNeeded(target: RenderTarget) {
175
        if (!dirty) {
176
            heldItemSubmits.clear()
177
            return
178
        }
179
180
        dirty = false
181
182
        try {
183
            renderTargetHolder.get()?.let { modes.activeMode.render(target, it) }
184
        } finally {
185
            heldItemSubmits.clear()
186
        }
187
    }
188
189
    override fun onDisabled() {
190
        dirty = false
191
        heldItemSubmits.clear()
192
        renderTargetHolder.close()
193
    }
194
195
    private object Normal : ChamsMode("Normal") {
196
        override fun render(target: RenderTarget, chamsTarget: RenderTarget) {
197
            val colorTexture = chamsTarget.colorTextureView ?: return
198
199
            target.createRenderPass({ "Chams blit pass" }, useDepthAttachment = false).use { pass ->
200
                pass.setPipeline(pipelineBlit)
201
                pass.bindTexture("InSampler", colorTexture, blitSampler)
202
                pass.draw(3, 1, 0, 0)
203
            }
204
        }
205
    }
206
207
    private object Image : ChamsMode("Image") {
208
        private val texture by file("File", supportedExtensions = PNG_AND_JPG).toTextureProperty(this)
209
        val mapping = modes("Mapping", Repeat, arrayOf(Repeat, Stretch, Cover))
210
        private val filtering by enumChoice("Filtering", ImageFiltering.NEAREST)
211
        private val offset by vec2f("Offset", Vector2f())
212
213
        private val imageUniform = CachedUniform<ImageUniform>(ClientUniformDefine.CHAMS) { value ->
214
            putVec2(value.scaleX, value.scaleY)
215
            putVec2(value.offsetX, value.offsetY)
216
        }
217
218
        override fun render(target: RenderTarget, chamsTarget: RenderTarget) {
219
            val colorTexture = chamsTarget.colorTextureView
220
            val chamsDepth = chamsTarget.depthTextureView
221
            val sceneDepth = target.depthTextureView
222
            val imageView = texture?.textureView
223
            if (colorTexture == null || chamsDepth == null || sceneDepth == null || imageView == null) {
224
                Normal.render(target, chamsTarget)
225
                return
226
            }
227
228
            val imageWidth = imageView.getWidth(0)
229
            val imageHeight = imageView.getHeight(0)
230
            val mappingData = mapping.activeMode.uniform(target.width, target.height, imageWidth, imageHeight)
231
            val imageData = mappingData.copy(
232
                offsetX = mappingData.offsetX + offset.x(),
233
                offsetY = mappingData.offsetY + offset.y(),
234
            )
235
            val sampler = filtering.sampler(mapping.activeMode.repeats)
236
            val ubo = imageUniform.get(imageData)
237
238
            target.createRenderPass({ "Chams image blit pass" }, useDepthAttachment = false).use { pass ->
239
                pass.setPipeline(ClientRenderPipelines.ChamsImage)
240
                pass.bindTexture("entityColor", colorTexture, blitSampler)
241
                pass.bindTexture("entityDepth", chamsDepth, blitSampler)
242
                pass.bindTexture("sceneDepth", sceneDepth, blitSampler)
243
                pass.bindTexture("image", imageView, sampler)
244
                pass.setUniform(ClientUniformDefine.CHAMS.uboName, ubo)
245
                pass.draw(3, 1, 0, 0)
246
            }
247
        }
248
    }
249
250
    private abstract class ChamsMode(name: String) : Mode(name) {
251
        override val parent: ModeValueGroup<*>
252
            get() = modes
253
254
        abstract fun render(target: RenderTarget, chamsTarget: RenderTarget)
255
    }
256
257
    private abstract class ImageMappingMode(name: String) : Mode(name) {
258
        override val parent: ModeValueGroup<*>
259
            get() = Image.mapping
260
261
        open val repeats: Boolean get() = false
262
263
        abstract fun uniform(targetWidth: Int, targetHeight: Int, imageWidth: Int, imageHeight: Int): ImageUniform
264
    }
265
266
    private object Repeat : ImageMappingMode("Repeat") {
267
        private val tileWidth by int("TileWidth", 256, 16..2048, "px")
268
269
        override val repeats: Boolean get() = true
270
271
        override fun uniform(targetWidth: Int, targetHeight: Int, imageWidth: Int, imageHeight: Int): ImageUniform {
272
            val width = tileWidth.toFloat()
273
            return ImageUniform(width, width * imageHeight / imageWidth)
274
        }
275
    }
276
277
    private object Stretch : ImageMappingMode("Stretch") {
278
        override fun uniform(targetWidth: Int, targetHeight: Int, imageWidth: Int, imageHeight: Int) =
279
            ImageUniform(targetWidth.toFloat(), targetHeight.toFloat())
280
    }
281
282
    private object Cover : ImageMappingMode("Cover") {
283
        override fun uniform(targetWidth: Int, targetHeight: Int, imageWidth: Int, imageHeight: Int): ImageUniform {
284
            val scale = maxOf(targetWidth.toFloat() / imageWidth, targetHeight.toFloat() / imageHeight)
285
            val width = imageWidth * scale
286
            val height = imageHeight * scale
287
            return ImageUniform(width, height, (targetWidth - width) * 0.5f, (targetHeight - height) * 0.5f)
288
        }
289
    }
290
291
    private enum class ImageFiltering(override val tag: String, val filterMode: FilterMode) : Tagged {
292
        NEAREST("Nearest", FilterMode.NEAREST),
293
        LINEAR("Linear", FilterMode.LINEAR),
294
        ;
295
296
        fun sampler(repeat: Boolean) = RenderSystem.getSamplerCache().let { cache ->
297
            if (repeat) cache.getRepeat(filterMode) else cache.getClampToEdge(filterMode)
298
        }
299
    }
300
301
}
302