nametags module

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

6 implementationsRenderRENDERVISUALS

Full module source: 6 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/Nametags.javaJava · 753 lines · 27.8 KB

Displays customizable nametags above players, items and other entities.

Settingsentitiesscaleignore-selfignore-friendsignore-botscullingculling-rangeculling-counthealthuse-display-namegamemodedistancepingitemsitem-spacingignore-empty-slotsdurabilitydisplay-enchantsshown-enchantmentsenchantment-positionenchant-name-lengthenchant-text-scaleshow-countbackground-colorname-colorping-colorgamemode-colordistance-color-modedistance-color
Nametags.javaJava · Minecraft 26.2 · 753 lines · 27.8 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 it.unimi.dsi.fastutil.objects.Object2IntMap;
9
import it.unimi.dsi.fastutil.objects.Object2IntMaps;
10
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
11
import meteordevelopment.meteorclient.events.render.Render2DEvent;
12
import meteordevelopment.meteorclient.events.world.TickEvent;
13
import meteordevelopment.meteorclient.renderer.Renderer2D;
14
import meteordevelopment.meteorclient.renderer.text.TextRenderer;
15
import meteordevelopment.meteorclient.settings.*;
16
import meteordevelopment.meteorclient.systems.config.Config;
17
import meteordevelopment.meteorclient.systems.friends.Friends;
18
import meteordevelopment.meteorclient.systems.modules.Categories;
19
import meteordevelopment.meteorclient.systems.modules.Module;
20
import meteordevelopment.meteorclient.systems.modules.Modules;
21
import meteordevelopment.meteorclient.systems.modules.player.NameProtect;
22
import meteordevelopment.meteorclient.utils.Utils;
23
import meteordevelopment.meteorclient.utils.entity.EntityUtils;
24
import meteordevelopment.meteorclient.utils.misc.Names;
25
import meteordevelopment.meteorclient.utils.player.PlayerUtils;
26
import meteordevelopment.meteorclient.utils.render.NametagUtils;
27
import meteordevelopment.meteorclient.utils.render.RenderUtils;
28
import meteordevelopment.meteorclient.utils.render.color.Color;
29
import meteordevelopment.meteorclient.utils.render.color.SettingColor;
30
import meteordevelopment.orbit.EventHandler;
31
import net.minecraft.client.gui.GuiGraphicsExtractor;
32
import net.minecraft.core.Holder;
33
import net.minecraft.resources.ResourceKey;
34
import net.minecraft.tags.EnchantmentTags;
35
import net.minecraft.util.Mth;
36
import net.minecraft.world.entity.*;
37
import net.minecraft.world.entity.decoration.ItemFrame;
38
import net.minecraft.world.entity.item.ItemEntity;
39
import net.minecraft.world.entity.item.PrimedTnt;
40
import net.minecraft.world.entity.player.Player;
41
import net.minecraft.world.entity.vehicle.minecart.MinecartTNT;
42
import net.minecraft.world.item.ItemStack;
43
import net.minecraft.world.item.enchantment.Enchantment;
44
import net.minecraft.world.item.enchantment.EnchantmentHelper;
45
import net.minecraft.world.item.enchantment.Enchantments;
46
import net.minecraft.world.item.enchantment.ItemEnchantments;
47
import net.minecraft.world.level.GameType;
48
import net.minecraft.world.phys.Vec3;
49
import org.joml.Vector3d;
50
51
import java.util.*;
52
53
public class Nametags extends Module {
54
    private final SettingGroup sgGeneral = settings.getDefaultGroup();
55
    private final SettingGroup sgPlayers = settings.createGroup("Players");
56
    private final SettingGroup sgItems = settings.createGroup("Items");
57
    private final SettingGroup sgRender = settings.createGroup("Render");
58
59
    // General
60
61
    private final Setting<Set<EntityType<?>>> entities = sgGeneral.add(new EntityTypeListSetting.Builder()
62
        .name("entities")
63
        .description("Select entities to draw nametags on.")
64
        .defaultValue(EntityTypes.PLAYER, EntityTypes.ITEM)
65
        .build()
66
    );
67
68
    private final Setting<Double> scale = sgGeneral.add(new DoubleSetting.Builder()
69
        .name("scale")
70
        .description("The scale of the nametag.")
71
        .defaultValue(1.1)
72
        .min(0.1)
73
        .build()
74
    );
75
76
    private final Setting<Boolean> ignoreSelf = sgGeneral.add(new BoolSetting.Builder()
77
        .name("ignore-self")
78
        .description("Ignore yourself when in third person or freecam.")
79
        .defaultValue(true)
80
        .build()
81
    );
82
83
    private final Setting<Boolean> ignoreFriends = sgGeneral.add(new BoolSetting.Builder()
84
        .name("ignore-friends")
85
        .description("Ignore rendering nametags for friends.")
86
        .defaultValue(false)
87
        .build()
88
    );
89
90
    private final Setting<Boolean> ignoreBots = sgGeneral.add(new BoolSetting.Builder()
91
        .name("ignore-bots")
92
        .description("Only render non-bot nametags.")
93
        .defaultValue(true)
94
        .build()
95
    );
96
97
    private final Setting<Boolean> culling = sgGeneral.add(new BoolSetting.Builder()
98
        .name("culling")
99
        .description("Only render a certain number of nametags at a certain distance.")
100
        .defaultValue(false)
101
        .build()
102
    );
103
104
    private final Setting<Double> maxCullRange = sgGeneral.add(new DoubleSetting.Builder()
105
        .name("culling-range")
106
        .description("Only render nametags within this distance of your player.")
107
        .defaultValue(20)
108
        .min(0)
109
        .sliderMax(200)
110
        .visible(culling::get)
111
        .build()
112
    );
113
114
    private final Setting<Integer> maxCullCount = sgGeneral.add(new IntSetting.Builder()
115
        .name("culling-count")
116
        .description("Only render this many nametags.")
117
        .defaultValue(50)
118
        .min(1)
119
        .sliderRange(1, 100)
120
        .visible(culling::get)
121
        .build()
122
    );
123
124
    //Players
125
126
    private final Setting<Boolean> displayHealth = sgPlayers.add(new BoolSetting.Builder()
127
        .name("health")
128
        .description("Shows the player's health.")
129
        .defaultValue(true)
130
        .build()
131
    );
132
133
    private final Setting<Boolean> displayPrefix = sgPlayers.add(new BoolSetting.Builder()
134
        .name("use-display-name")
135
        .description("Uses the players server display name instead of their account name.")
136
        .defaultValue(false)
137
        .build()
138
    );
139
140
    private final Setting<Boolean> displayGameMode = sgPlayers.add(new BoolSetting.Builder()
141
        .name("gamemode")
142
        .description("Shows the player's GameMode.")
143
        .defaultValue(false)
144
        .build()
145
    );
146
147
    private final Setting<Boolean> displayDistance = sgPlayers.add(new BoolSetting.Builder()
148
        .name("distance")
149
        .description("Shows the distance between you and the player.")
150
        .defaultValue(false)
151
        .build()
152
    );
153
154
    private final Setting<Boolean> displayPing = sgPlayers.add(new BoolSetting.Builder()
155
        .name("ping")
156
        .description("Shows the player's ping.")
157
        .defaultValue(true)
158
        .build()
159
    );
160
161
    private final Setting<Boolean> displayItems = sgPlayers.add(new BoolSetting.Builder()
162
        .name("items")
163
        .description("Displays armor and hand items above the name tags.")
164
        .defaultValue(true)
165
        .build()
166
    );
167
168
    private final Setting<Double> itemSpacing = sgPlayers.add(new DoubleSetting.Builder()
169
        .name("item-spacing")
170
        .description("The spacing between items.")
171
        .defaultValue(2)
172
        .range(0, 10)
173
        .visible(displayItems::get)
174
        .build()
175
    );
176
177
    private final Setting<Boolean> ignoreEmpty = sgPlayers.add(new BoolSetting.Builder()
178
        .name("ignore-empty-slots")
179
        .description("Doesn't add spacing where an empty item stack would be.")
180
        .defaultValue(true)
181
        .visible(displayItems::get)
182
        .build()
183
    );
184
185
    private final Setting<Durability> itemDurability = sgPlayers.add(new EnumSetting.Builder<Durability>()
186
        .name("durability")
187
        .description("Displays item durability as either a total, percentage, or neither.")
188
        .defaultValue(Durability.None)
189
        .visible(displayItems::get)
190
        .build()
191
    );
192
193
    private final Setting<Boolean> displayEnchants = sgPlayers.add(new BoolSetting.Builder()
194
        .name("display-enchants")
195
        .description("Displays item enchantments on the items.")
196
        .defaultValue(false)
197
        .visible(displayItems::get)
198
        .build()
199
    );
200
201
    private final Setting<Set<ResourceKey<Enchantment>>> shownEnchantments = sgPlayers.add(new EnchantmentListSetting.Builder()
202
        .name("shown-enchantments")
203
        .description("The enchantments that are shown on nametags.")
204
        .visible(() -> displayItems.get() && displayEnchants.get())
205
        .defaultValue(
206
            Enchantments.PROTECTION,
207
            Enchantments.BLAST_PROTECTION,
208
            Enchantments.FIRE_PROTECTION,
209
            Enchantments.PROJECTILE_PROTECTION
210
        )
211
        .build()
212
    );
213
214
    private final Setting<Position> enchantPos = sgPlayers.add(new EnumSetting.Builder<Position>()
215
        .name("enchantment-position")
216
        .description("Where the enchantments are rendered.")
217
        .defaultValue(Position.Above)
218
        .visible(() -> displayItems.get() && displayEnchants.get())
219
        .build()
220
    );
221
222
    private final Setting<Integer> enchantLength = sgPlayers.add(new IntSetting.Builder()
223
        .name("enchant-name-length")
224
        .description("The length enchantment names are trimmed to.")
225
        .defaultValue(3)
226
        .range(1, 5)
227
        .sliderRange(1, 5)
228
        .visible(() -> displayItems.get() && displayEnchants.get())
229
        .build()
230
    );
231
232
    private final Setting<Double> enchantTextScale = sgPlayers.add(new DoubleSetting.Builder()
233
        .name("enchant-text-scale")
234
        .description("The scale of the enchantment text.")
235
        .defaultValue(1)
236
        .range(0.1, 2)
237
        .sliderRange(0.1, 2)
238
        .visible(() -> displayItems.get() && displayEnchants.get())
239
        .build()
240
    );
241
242
    //Items
243
244
    private final Setting<Boolean> itemCount = sgItems.add(new BoolSetting.Builder()
245
        .name("show-count")
246
        .description("Displays the number of items in the stack.")
247
        .defaultValue(true)
248
        .build()
249
    );
250
251
    // Render
252
253
    private final Setting<SettingColor> background = sgRender.add(new ColorSetting.Builder()
254
        .name("background-color")
255
        .description("The color of the nametag background.")
256
        .defaultValue(new SettingColor(0, 0, 0, 75))
257
        .build()
258
    );
259
260
    private final Setting<SettingColor> nameColor = sgRender.add(new ColorSetting.Builder()
261
        .name("name-color")
262
        .description("The color of the nametag names.")
263
        .defaultValue(new SettingColor())
264
        .build()
265
    );
266
267
    private final Setting<SettingColor> pingColor = sgRender.add(new ColorSetting.Builder()
268
        .name("ping-color")
269
        .description("The color of the nametag ping.")
270
        .defaultValue(new SettingColor(20, 170, 170))
271
        .visible(displayPing::get)
272
        .build()
273
    );
274
275
    private final Setting<SettingColor> gamemodeColor = sgRender.add(new ColorSetting.Builder()
276
        .name("gamemode-color")
277
        .description("The color of the nametag gamemode.")
278
        .defaultValue(new SettingColor(232, 185, 35))
279
        .visible(displayGameMode::get)
280
        .build()
281
    );
282
283
    private final Setting<DistanceColorMode> distanceColorMode = sgRender.add(new EnumSetting.Builder<DistanceColorMode>()
284
        .name("distance-color-mode")
285
        .description("The mode to color the nametag distance with.")
286
        .defaultValue(DistanceColorMode.Gradient)
287
        .visible(displayDistance::get)
288
        .build()
289
    );
290
291
    private final Setting<SettingColor> distanceColor = sgRender.add(new ColorSetting.Builder()
292
        .name("distance-color")
293
        .description("The color of the nametag distance.")
294
        .defaultValue(new SettingColor(150, 150, 150))
295
        .visible(() -> displayDistance.get() && distanceColorMode.get() == DistanceColorMode.Flat)
296
        .build()
297
    );
298
299
    private final Color WHITE = new Color(255, 255, 255);
300
    private final Color RED = new Color(255, 25, 25);
301
    private final Color AMBER = new Color(255, 105, 25);
302
    private final Color GREEN = new Color(25, 252, 25);
303
    private final Color GOLD = new Color(232, 185, 35);
304
305
    private final Vector3d pos = new Vector3d();
306
    private final double[] itemWidths = new double[6];
307
308
    private final List<Entity> entityList = new ArrayList<>();
309
310
    public Nametags() {
311
        super(Categories.Render, "nametags", "Displays customizable nametags above players, items and other entities.");
312
    }
313
314
    private static String ticksToTime(int ticks) {
315
        if (ticks > 20 * 3600) {
316
            int h = ticks / 20 / 3600;
317
            return h + " h";
318
        } else if (ticks > 20 * 60) {
319
            int m = ticks / 20 / 60;
320
            return m + " m";
321
        } else {
322
            int s = ticks / 20;
323
            int ms = (ticks % 20) / 2;
324
            return s + "." + ms + " s";
325
        }
326
    }
327
328
    @EventHandler
329
    private void onTick(TickEvent.Post event) {
330
        entityList.clear();
331
332
        boolean freecamNotActive = !Modules.get().isActive(Freecam.class);
333
        boolean notThirdPerson = mc.options.getCameraType().isFirstPerson();
334
        Vec3 cameraPos = mc.gameRenderer.mainCamera().position();
335
336
        for (Entity entity : mc.level.entitiesForRendering()) {
337
            EntityType<?> type = entity.getType();
338
            if (!entities.get().contains(type)) continue;
339
340
            if (type == EntityTypes.PLAYER) {
341
                if ((ignoreSelf.get() || (freecamNotActive && notThirdPerson)) && entity == mc.player) continue;
342
                if (EntityUtils.getGameMode((Player) entity) == null && ignoreBots.get()) continue;
343
                if (Friends.get().isFriend((Player) entity) && ignoreFriends.get()) continue;
344
            }
345
346
            if (!culling.get() || PlayerUtils.isWithinCamera(entity, maxCullRange.get())) {
347
                entityList.add(entity);
348
            }
349
        }
350
351
        entityList.sort(Comparator.comparing(e -> e.distanceToSqr(cameraPos)));
352
    }
353
354
    @EventHandler
355
    private void onRender2D(Render2DEvent event) {
356
        int count = getRenderCount();
357
        boolean shadow = Config.get().customFont.get();
358
359
        for (int i = count - 1; i > -1; i--) {
360
            Entity entity = entityList.get(i);
361
362
            Utils.set(pos, entity, event.tickDelta);
363
            pos.add(0, getHeight(entity), 0);
364
365
            if (NametagUtils.to2D(pos, scale.get())) {
366
                switch (entity) {
367
                    case Player player -> renderNametagPlayer(event, player, shadow);
368
                    case ItemEntity item -> renderNametagItem(event.graphics, item.getItem(), shadow);
369
                    case ItemFrame itemFrame -> renderNametagItem(event.graphics, itemFrame.getItem(), shadow);
370
                    case PrimedTnt tnt -> renderTntNametag(event.graphics, ticksToTime(tnt.getFuse()), shadow);
371
                    case MinecartTNT minecartTNT -> renderTntNametag(event.graphics, ticksToTime(minecartTNT.getFuse()), shadow);
372
                    case LivingEntity living -> renderGenericLivingNametag(event.graphics, living, shadow);
373
                    default -> renderGenericNametag(event.graphics, entity, shadow);
374
                }
375
            }
376
        }
377
    }
378
379
    private int getRenderCount() {
380
        int count = culling.get() ? maxCullCount.get() : entityList.size();
381
        count = Mth.clamp(count, 0, entityList.size());
382
383
        return count;
384
    }
385
386
    @Override
387
    public String getInfoString() {
388
        return Integer.toString(getRenderCount());
389
    }
390
391
    private double getHeight(Entity entity) {
392
        double height = entity.getEyeHeight(entity.getPose());
393
394
        if (entity.getType() == EntityTypes.ITEM || entity.getType() == EntityTypes.ITEM_FRAME || entity.getType() == EntityTypes.GLOW_ITEM_FRAME)
395
            height += 0.2;
396
        else height += 0.5;
397
398
        return height;
399
    }
400
401
    private void renderNametagPlayer(Render2DEvent event, Player player, boolean shadow) {
402
        TextRenderer text = TextRenderer.get();
403
        NametagUtils.begin(pos, event.graphics);
404
405
        // Gamemode
406
        GameType gm = EntityUtils.getGameMode(player);
407
        String gmText = "BOT";
408
        if (gm != null) {
409
            gmText = switch (gm) {
410
                case SPECTATOR -> "Sp";
411
                case SURVIVAL -> "S";
412
                case CREATIVE -> "C";
413
                case ADVENTURE -> "A";
414
            };
415
        }
416
417
        gmText = "[" + gmText + "] ";
418
419
        // Name
420
        String name;
421
        Color nameColor = PlayerUtils.getPlayerColor(player, this.nameColor.get());
422
423
        if (player == mc.player) name = Modules.get().get(NameProtect.class).getName(player.getName().getString());
424
        else {
425
            if (displayPrefix.get()) name = player.getDisplayName().getString();
426
            else name = player.getName().getString();
427
        }
428
429
        // Health
430
        float absorption = player.getAbsorptionAmount();
431
        int health = Math.round(player.getHealth() + absorption);
432
        double healthPercentage = health / (player.getMaxHealth() + absorption);
433
434
        String healthText = " " + health;
435
        Color healthColor;
436
437
        if (healthPercentage <= 0.333) healthColor = RED;
438
        else if (healthPercentage <= 0.666) healthColor = AMBER;
439
        else healthColor = GREEN;
440
441
        // Ping
442
        int ping = EntityUtils.getPing(player);
443
        String pingText = " [" + ping + "ms]";
444
445
        // Distance
446
        double dist = Math.round(PlayerUtils.distanceToCamera(player) * 10.0) / 10.0;
447
        String distText = " " + dist + "m";
448
449
        // Calc widths
450
        double gmWidth = text.getWidth(gmText, shadow);
451
        double nameWidth = text.getWidth(name, shadow);
452
        double healthWidth = text.getWidth(healthText, shadow);
453
        double pingWidth = text.getWidth(pingText, shadow);
454
        double distWidth = text.getWidth(distText, shadow);
455
456
        double width = nameWidth;
457
458
        boolean renderPlayerDistance = player != mc.getCameraEntity() || Modules.get().isActive(Freecam.class);
459
460
        if (displayHealth.get()) width += healthWidth;
461
        if (displayGameMode.get()) width += gmWidth;
462
        if (displayPing.get()) width += pingWidth;
463
        if (displayDistance.get() && renderPlayerDistance) width += distWidth;
464
465
        double widthHalf = width / 2;
466
        double heightDown = text.getHeight(shadow);
467
468
        drawBg(-widthHalf, -heightDown, width, heightDown);
469
470
        // Render texts
471
        text.beginBig(event.graphics);
472
        double hX = -widthHalf;
473
        double hY = -heightDown;
474
475
        if (displayGameMode.get()) hX = text.render(gmText, hX, hY, gamemodeColor.get(), shadow);
476
        hX = text.render(name, hX, hY, nameColor, shadow);
477
478
        if (displayHealth.get()) hX = text.render(healthText, hX, hY, healthColor, shadow);
479
        if (displayPing.get()) hX = text.render(pingText, hX, hY, pingColor.get(), shadow);
480
        if (displayDistance.get() && renderPlayerDistance) {
481
            switch (distanceColorMode.get()) {
482
                case Flat -> text.render(distText, hX, hY, distanceColor.get(), shadow);
483
                case Gradient -> text.render(distText, hX, hY, EntityUtils.getColorFromDistance(player), shadow);
484
            }
485
        }
486
487
        text.end();
488
489
        if (displayItems.get()) {
490
            // Item calc
491
            Arrays.fill(itemWidths, 0);
492
            boolean hasItems = false;
493
            int maxEnchantCount = 0;
494
495
            for (int i = 0; i < 6; i++) {
496
                ItemStack itemStack = getItem(player, i);
497
498
                // Setting up widths
499
                if (itemWidths[i] == 0 && (!ignoreEmpty.get() || !itemStack.isEmpty()))
500
                    itemWidths[i] = 32 + itemSpacing.get();
501
502
                if (!itemStack.isEmpty()) hasItems = true;
503
504
                if (displayEnchants.get()) {
505
                    ItemEnchantments enchantments = EnchantmentHelper.getEnchantmentsForCrafting(itemStack);
506
507
                    int size = 0;
508
                    for (Holder<Enchantment> enchantment : enchantments.keySet()) {
509
                        if (enchantment.unwrapKey().isPresent() && !shownEnchantments.get().contains(enchantment.unwrapKey().get()))
510
                            continue;
511
                        String enchantName = Utils.getEnchantSimpleName(enchantment, enchantLength.get()) + " " + enchantments.getLevel(enchantment);
512
                        itemWidths[i] = Math.max(itemWidths[i], (text.getWidth(enchantName, shadow) / 2));
513
                        size++;
514
                    }
515
516
                    maxEnchantCount = Math.max(maxEnchantCount, size);
517
                }
518
            }
519
520
            double itemsHeight = (hasItems ? 32 : 0);
521
            double itemWidthTotal = 0;
522
            for (double w : itemWidths) itemWidthTotal += w;
523
            double itemWidthHalf = itemWidthTotal / 2;
524
525
            double y = -heightDown - 7 - itemsHeight;
526
            double x = -itemWidthHalf;
527
528
            // Rendering items and enchants
529
            for (int i = 0; i < 6; i++) {
530
                ItemStack stack = getItem(player, i);
531
532
                RenderUtils.drawItem(event.graphics, stack, (int) x, (int) y, 2, true, null, false);
533
534
                if (stack.isDamageableItem() && itemDurability.get() != Durability.None) {
535
                    text.begin(event.graphics, 0.75, false, true);
536
537
                    String damageText = switch (itemDurability.get()) {
538
                        case Percentage ->
539
                            String.format("%.0f%%", ((stack.getMaxDamage() - stack.getDamageValue()) * 100f) / stack.getMaxDamage());
540
                        case Total -> Integer.toString(stack.getMaxDamage() - stack.getDamageValue());
541
                        default -> "err";
542
                    };
543
                    Color damageColor = new Color(stack.getBarColor());
544
545
                    text.render(damageText, (int) x, (int) y, damageColor.a(255), true);
546
                    text.end();
547
                }
548
549
                if (maxEnchantCount > 0 && displayEnchants.get()) {
550
                    text.begin(event.graphics, 0.5 * enchantTextScale.get(), false, true);
551
552
                    ItemEnchantments enchantments = EnchantmentHelper.getEnchantmentsForCrafting(stack);
553
                    Object2IntMap<Holder<Enchantment>> enchantmentsToShow = new Object2IntOpenHashMap<>();
554
555
                    for (Holder<Enchantment> enchantment : enchantments.keySet()) {
556
                        if (enchantment.is(shownEnchantments.get()::contains)) {
557
                            enchantmentsToShow.put(enchantment, enchantments.getLevel(enchantment));
558
                        }
559
                    }
560
561
                    double aW = itemWidths[i];
562
                    double enchantY = 0;
563
564
                    double addY = switch (enchantPos.get()) {
565
                        case Above -> -((enchantmentsToShow.size() + 1) * text.getHeight(shadow));
566
                        case OnTop -> (itemsHeight - enchantmentsToShow.size() * text.getHeight(shadow)) / 2;
567
                    };
568
569
                    double enchantX;
570
571
                    for (Object2IntMap.Entry<Holder<Enchantment>> entry : Object2IntMaps.fastIterable(enchantmentsToShow)) {
572
                        String enchantName = Utils.getEnchantSimpleName(entry.getKey(), enchantLength.get()) + " " + entry.getIntValue();
573
574
                        Color enchantColor = WHITE;
575
                        if (entry.getKey().is(EnchantmentTags.CURSE)) enchantColor = RED;
576
577
                        enchantX = switch (enchantPos.get()) {
578
                            case Above -> x + (aW / 2) - (text.getWidth(enchantName, shadow) / 2);
579
                            case OnTop -> x + (aW - text.getWidth(enchantName, shadow)) / 2;
580
                        };
581
582
                        text.render(enchantName, enchantX, y + addY + enchantY, enchantColor, shadow);
583
584
                        enchantY += text.getHeight(shadow);
585
                    }
586
587
                    text.end();
588
                }
589
590
                x += itemWidths[i];
591
            }
592
        } else if (displayEnchants.get()) displayEnchants.set(false);
593
594
        NametagUtils.end(event.graphics);
595
    }
596
597
    private void renderNametagItem(GuiGraphicsExtractor graphics, ItemStack stack, boolean shadow) {
598
        if (stack.isEmpty()) return;
599
600
        TextRenderer text = TextRenderer.get();
601
        NametagUtils.begin(pos, graphics);
602
603
        String name = Names.get(stack);
604
        String count = " x" + stack.getCount();
605
606
        double nameWidth = text.getWidth(name, shadow);
607
        double countWidth = text.getWidth(count, shadow);
608
        double heightDown = text.getHeight(shadow);
609
610
        double width = nameWidth;
611
        if (itemCount.get()) width += countWidth;
612
        double widthHalf = width / 2;
613
614
        drawBg(-widthHalf, -heightDown, width, heightDown);
615
616
        text.beginBig(graphics);
617
        double hX = -widthHalf;
618
        double hY = -heightDown;
619
620
        hX = text.render(name, hX, hY, nameColor.get(), shadow);
621
        if (itemCount.get()) text.render(count, hX, hY, GOLD, shadow);
622
        text.end();
623
624
        NametagUtils.end(graphics);
625
    }
626
627
    private void renderGenericLivingNametag(GuiGraphicsExtractor graphics, LivingEntity entity, boolean shadow) {
628
        TextRenderer text = TextRenderer.get();
629
        NametagUtils.begin(pos, graphics);
630
631
        //Name
632
        String nameText = entity.getType().getDescription().getString();
633
        nameText += " ";
634
635
        //Health
636
        float absorption = entity.getAbsorptionAmount();
637
        int health = Math.round(entity.getHealth() + absorption);
638
        double healthPercentage = health / (entity.getMaxHealth() + absorption);
639
640
        String healthText = String.valueOf(health);
641
        Color healthColor;
642
643
        if (healthPercentage <= 0.333) healthColor = RED;
644
        else if (healthPercentage <= 0.666) healthColor = AMBER;
645
        else healthColor = GREEN;
646
647
        double nameWidth = text.getWidth(nameText, shadow);
648
        double healthWidth = text.getWidth(healthText, shadow);
649
        double heightDown = text.getHeight(shadow);
650
651
        double width = nameWidth + healthWidth;
652
        double widthHalf = width / 2;
653
654
        drawBg(-widthHalf, -heightDown, width, heightDown);
655
656
        text.beginBig(graphics);
657
        double hX = -widthHalf;
658
        double hY = -heightDown;
659
660
        hX = text.render(nameText, hX, hY, nameColor.get(), shadow);
661
        text.render(healthText, hX, hY, healthColor, shadow);
662
        text.end();
663
664
        NametagUtils.end(graphics);
665
    }
666
667
    private void renderGenericNametag(GuiGraphicsExtractor graphics, Entity entity, boolean shadow) {
668
        TextRenderer text = TextRenderer.get();
669
        NametagUtils.begin(pos, graphics);
670
671
        //Name
672
        String nameText = entity.getType().getDescription().getString();
673
674
        double nameWidth = text.getWidth(nameText, shadow);
675
        double heightDown = text.getHeight(shadow);
676
        double widthHalf = nameWidth / 2;
677
678
        drawBg(-widthHalf, -heightDown, nameWidth, heightDown);
679
680
        text.beginBig(graphics);
681
        double hX = -widthHalf;
682
        double hY = -heightDown;
683
684
        text.render(nameText, hX, hY, nameColor.get(), shadow);
685
        text.end();
686
687
        NametagUtils.end(graphics);
688
    }
689
690
    private void renderTntNametag(GuiGraphicsExtractor graphics, String fuseText, boolean shadow) {
691
        TextRenderer text = TextRenderer.get();
692
        NametagUtils.begin(pos, graphics);
693
694
        double width = text.getWidth(fuseText, shadow);
695
        double heightDown = text.getHeight(shadow);
696
697
        double widthHalf = width / 2;
698
699
        drawBg(-widthHalf, -heightDown, width, heightDown);
700
701
        text.beginBig(graphics);
702
        double hX = -widthHalf;
703
        double hY = -heightDown;
704
705
        text.render(fuseText, hX, hY, nameColor.get(), shadow);
706
        text.end();
707
708
        NametagUtils.end(graphics);
709
    }
710
711
    private ItemStack getItem(Player entity, int index) {
712
        return switch (index) {
713
            case 0 -> entity.getMainHandItem();
714
            case 1 -> entity.getItemBySlot(EquipmentSlot.HEAD);
715
            case 2 -> entity.getItemBySlot(EquipmentSlot.CHEST);
716
            case 3 -> entity.getItemBySlot(EquipmentSlot.LEGS);
717
            case 4 -> entity.getItemBySlot(EquipmentSlot.FEET);
718
            case 5 -> entity.getOffhandItem();
719
            default -> ItemStack.EMPTY;
720
        };
721
    }
722
723
    private void drawBg(double x, double y, double width, double height) {
724
        Renderer2D.COLOR.begin();
725
        Renderer2D.COLOR.quad(x - 1, y - 1, width + 2, height + 2, background.get());
726
        Renderer2D.COLOR.render();
727
    }
728
729
    public enum Position {
730
        Above,
731
        OnTop
732
    }
733
734
    public enum Durability {
735
        None,
736
        Total,
737
        Percentage
738
    }
739
740
    public enum DistanceColorMode {
741
        Gradient,
742
        Flat
743
    }
744
745
    public boolean excludeBots() {
746
        return ignoreBots.get();
747
    }
748
749
    public boolean playerNametags() {
750
        return isActive() && entities.get().contains(EntityTypes.PLAYER);
751
    }
752
}
753
MelaHack (ThunderHack fork)RENDERsrc/main/java/thunder/hack/features/modules/render/NameTags.javaJava · 660 lines · 34.5 KB

Draws important info about the player.

SettingsSelfScaleResizeHeightGamemodeSpawnerNameTagEntityOwnerPingHPDistanceTotemPopsOutlineTypeFriendOutlineOutlineColorFriendOutlineColorEnchantsOnlyHandsFunTimeHpIgnoreBotsPotionsShulkersFillFriendFillFontModeArmorModeHealth
NameTags.javaJava · Minecraft 26.2 · 660 lines · 34.5 KB · complete file, verbatimOriginal ↗
1
package thunder.hack.features.modules.render;
2
import com.google.common.collect.Ordering;
3
import com.mojang.blaze3d.platform.GlStateManager;
4
import thunder.hack.utility.render.compat.RenderSystem;
5
import org.jetbrains.annotations.NotNull;
6
import org.joml.Vector4d;
7
import org.lwjgl.opengl.GL11;
8
import thunder.hack.core.Managers;
9
import thunder.hack.core.manager.player.FriendManager;
10
import thunder.hack.core.manager.client.ModuleManager;
11
import thunder.hack.gui.font.FontRenderers;
12
import thunder.hack.features.hud.impl.PotionHud;
13
import thunder.hack.features.modules.Module;
14
import thunder.hack.features.modules.client.HudEditor;
15
import thunder.hack.features.modules.misc.NameProtect;
16
import thunder.hack.setting.Setting;
17
import thunder.hack.setting.impl.ColorSetting;
18
import thunder.hack.utility.render.Render2DEngine;
19
import thunder.hack.utility.render.Render3DEngine;
20
import thunder.hack.utility.render.TextureStorage;
21
import java.util.List;
22
23
import java.awt.*;
24
import java.math.BigDecimal;
25
import java.math.RoundingMode;
26
import java.util.*;
27
import net.minecraft.ChatFormatting;
28
import net.minecraft.client.gui.GuiGraphicsExtractor;
29
import net.minecraft.client.multiplayer.PlayerInfo;
30
import net.minecraft.core.component.DataComponents;
31
import net.minecraft.core.registries.Registries;
32
import net.minecraft.network.chat.MutableComponent;
33
import net.minecraft.network.chat.numbers.StyledFormat;
34
import net.minecraft.resources.Identifier;
35
import net.minecraft.resources.ResourceKey;
36
import net.minecraft.util.Mth;
37
import net.minecraft.world.effect.MobEffectInstance;
38
import net.minecraft.world.entity.Entity;
39
import net.minecraft.world.entity.TamableAnimal;
40
import net.minecraft.world.entity.ai.attributes.Attributes;
41
import net.minecraft.world.entity.animal.equine.Horse;
42
import net.minecraft.world.entity.player.Player;
43
import net.minecraft.world.entity.projectile.Projectile;
44
import net.minecraft.world.item.BlockItem;
45
import net.minecraft.world.item.Item;
46
import net.minecraft.world.item.ItemStack;
47
import net.minecraft.world.item.component.ItemContainerContents;
48
import net.minecraft.world.item.enchantment.Enchantment;
49
import net.minecraft.world.item.enchantment.EnchantmentHelper;
50
import net.minecraft.world.item.enchantment.Enchantments;
51
import net.minecraft.world.item.enchantment.ItemEnchantments;
52
import net.minecraft.world.level.GameType;
53
import net.minecraft.world.level.block.ShulkerBoxBlock;
54
import net.minecraft.world.level.block.entity.BlockEntity;
55
import net.minecraft.world.level.block.entity.SpawnerBlockEntity;
56
import net.minecraft.world.phys.Vec3;
57
import net.minecraft.world.scores.DisplaySlot;
58
import net.minecraft.world.scores.Objective;
59
import net.minecraft.world.scores.ReadOnlyScoreInfo;
60
61
public class NameTags extends Module {
62
    private final Map<ResourceKey<Enchantment>, String> encMap = new HashMap<>();
63
64
    public NameTags() {
65
        super("NameTags", Category.RENDER);
66
        encMap.put(Enchantments.BLAST_PROTECTION, "B");
67
        encMap.put(Enchantments.PROTECTION, "P");
68
        encMap.put(Enchantments.SHARPNESS, "S");
69
        encMap.put(Enchantments.EFFICIENCY, "E");
70
        encMap.put(Enchantments.UNBREAKING, "U");
71
        encMap.put(Enchantments.POWER, "PO");
72
        encMap.put(Enchantments.THORNS, "T");
73
    }
74
75
    private final Setting<Boolean> self = new Setting<>("Self", false);
76
    private final Setting<Float> scale = new Setting<>("Scale", 1f, 0.1f, 10f);
77
    private final Setting<Boolean> resize = new Setting<>("Resize", false);
78
    private final Setting<Float> height = new Setting<>("Height", 2f, 0.1f, 10f);
79
    private final Setting<Boolean> gamemode = new Setting<>("Gamemode", false);
80
    private final Setting<Boolean> spawners = new Setting<>("SpawnerNameTag", false);
81
    private final Setting<Boolean> entityOwner = new Setting<>("EntityOwner", false);
82
    private final Setting<Boolean> ping = new Setting<>("Ping", false);
83
    private final Setting<Boolean> hp = new Setting<>("HP", true);
84
    private final Setting<Boolean> distance = new Setting<>("Distance", true);
85
    private final Setting<Boolean> pops = new Setting<>("TotemPops", true);
86
    private final Setting<OutlineColor> outline = new Setting<>("OutlineType", OutlineColor.New);
87
    private final Setting<OutlineColor> friendOutline = new Setting<>("FriendOutline", OutlineColor.None);
88
    private final Setting<ColorSetting> outlineColor = new Setting<>("OutlineColor", new ColorSetting(0x80000000));
89
    private final Setting<ColorSetting> friendOutlineColor = new Setting<>("FriendOutlineColor", new ColorSetting(0x80000000));
90
    private final Setting<Boolean> enchantss = new Setting<>("Enchants", true);
91
    private final Setting<Boolean> onlyHands = new Setting<>("OnlyHands", false, v -> enchantss.getValue());
92
    private final Setting<Boolean> funtimeHp = new Setting<>("FunTimeHp", false);
93
    private final Setting<Boolean> ignoreBots = new Setting<>("IgnoreBots", false);
94
    private final Setting<Boolean> potions = new Setting<>("Potions", true);
95
    private final Setting<Boolean> shulkers = new Setting<>("Shulkers", true);
96
    private final Setting<ColorSetting> fillColorA = new Setting<>("Fill", new ColorSetting(0x80000000));
97
    private final Setting<ColorSetting> fillColorF = new Setting<>("FriendFill", new ColorSetting(0x80000000));
98
    private final Setting<Font> font = new Setting<>("FontMode", Font.Fancy);
99
    private final Setting<Armor> armorMode = new Setting<>("ArmorMode", Armor.Full);
100
    private final Setting<Health> health = new Setting<>("Health", Health.Number);
101
102
103
    public void onRender2D(GuiGraphicsExtractor context) {
104
        if (false) return;
105
        for (Player ent : mc.level.players()) {
106
            if (ent == mc.player && (mc.options.getCameraType().isFirstPerson() || !self.getValue())) continue;
107
            if (getEntityPing(ent) <= 0 && ignoreBots.getValue()) continue;
108
109
            double x = ent.xo + (ent.getX() - ent.xo) * Render3DEngine.getTickDelta();
110
            double y = ent.yo + (ent.getY() - ent.yo) * Render3DEngine.getTickDelta();
111
            double z = ent.zo + (ent.getZ() - ent.zo) * Render3DEngine.getTickDelta();
112
            float scale = resize.getValue() ? this.scale.getValue() / mc.player.distanceTo(ent) : this.scale.getValue();
113
            Vec3 vector = new Vec3(x, y + height.getValue(), z);
114
115
            Vector4d position = null;
116
117
            vector = Render3DEngine.worldSpaceToScreenSpace(vector);
118
            if (vector.z > 0 && vector.z < 1) {
119
                position = new Vector4d(vector.x, vector.y, vector.z, 0);
120
                position.x = Math.min(vector.x, position.x);
121
                position.y = Math.min(vector.y, position.y);
122
                position.z = Math.max(vector.x, position.z);
123
            }
124
125
            String final_string = "";
126
127
            if (ping.getValue()) final_string += getPingColor(getEntityPing(ent)) + getEntityPing(ent) + "ms " + ChatFormatting.WHITE;
128
            if (gamemode.getValue()) final_string += translateGamemode(getEntityGamemode(ent)) + " ";
129
130
            if (FriendManager.friends.stream().anyMatch(i -> i.contains(ent.getDisplayName().getString())) && NameProtect.hideFriends.getValue() && ModuleManager.nameProtect.isEnabled()) {
131
                final_string += NameProtect.getCustomName() + " ";
132
            } else {
133
                final_string += ent.getDisplayName().getString() + " ";
134
            }
135
136
            if (hp.getValue() && health.is(Health.Number)) {
137
                final_string += getHealthColor(getHealth(ent)) + round2(getHealth(ent)) + " ";
138
            }
139
140
            if (distance.getValue()) final_string += String.format("%.1f", mc.player.distanceTo(ent)) + "m ";
141
            if (pops.getValue() && Managers.COMBAT.getPops(ent) != 0)
142
                final_string += (ChatFormatting.RESET + "" + Managers.COMBAT.getPops(ent));
143
144
            if (position != null) {
145
                double posX = position.x;
146
                double posY = position.y;
147
                double endPosX = position.z;
148
                double maxEnchantY = 0;
149
150
                float diff = (float) (endPosX - posX) / 2;
151
                float textWidth;
152
153
                if (font.getValue() == Font.Fancy) textWidth = (FontRenderers.sf_bold.getStringWidth(final_string) * 1);
154
                else textWidth = mc.font.width(final_string);
155
156
                float tagX = (float) ((posX + diff - textWidth / 2) * 1);
157
158
                ArrayList<ItemStack> stacks = new ArrayList<>();
159
160
                if (armorMode.getValue() != Armor.Durability) stacks.add(ent.getOffhandItem());
161
162
                stacks.addAll(thunder.hack.utility.player.ArmorUtility.getArmorItems(ent));
163
164
                if (armorMode.getValue() != Armor.Durability) stacks.add(ent.getMainHandItem());
165
166
                context.pose().pushMatrix();
167
                context.pose().translate((float) (tagX - 2 + (textWidth + 4) / 2f), (float) ((float) (posY - 13f) + 6.5f));
168
                context.pose().scale(scale, scale);
169
                context.pose().translate((float) (-(tagX - 2 + (textWidth + 4) / 2f)), (float) (-(float) ((posY - 13f) + 6.5f)));
170
171
                float item_offset = 0;
172
                if (armorMode.getValue() != Armor.None) for (ItemStack armorComponent : stacks) {
173
                    if (!armorComponent.isEmpty()) {
174
                        if (armorMode.getValue() == Armor.Full) {
175
                            context.pose().pushMatrix();
176
                            context.pose().translate((float) (posX - 55 + item_offset), (float) ((float) (posY - 33f)));
177
                            context.pose().scale(1.1f, 1.1f);
178
                            context.item(armorComponent, 0, 0);
179
                            context.itemDecorations(mc.font, armorComponent, 0, 0);
180
                            context.pose().popMatrix();
181
                        } else {
182
                            context.pose().pushMatrix();
183
                            context.pose().translate((float) (posX - 35 + item_offset), (float) ((float) (posY - 20)));
184
                            context.pose().scale(0.7f, 0.7f);
185
186
                            float durability = armorComponent.getMaxDamage() - armorComponent.getDamageValue();
187
                            int percent = (int) ((durability / (float) armorComponent.getMaxDamage()) * 100F);
188
189
                            Color color;
190
                            if (percent < 33) {
191
                                color = Color.RED;
192
                            } else if (percent > 33 && percent < 66) {
193
                                color = Color.YELLOW;
194
                            } else {
195
                                color = Color.GREEN;
196
                            }
197
                            context.text(mc.font, percent + "%", 0, 0, color.getRGB(), false);
198
                            context.pose().popMatrix();
199
                        }
200
201
                        float enchantmentY = 0;
202
203
                        ItemEnchantments enchants = EnchantmentHelper.getEnchantmentsForCrafting(armorComponent);
204
205
206
                        if (enchantss.getValue()) {
207
                            if (!onlyHands.getValue() || (armorComponent == ent.getOffhandItem() || armorComponent == ent.getMainHandItem())) {
208
                                var enchantments = mc.level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT);
209
                                for (ResourceKey<Enchantment> enchantment : encMap.keySet()) {
210
                                    if (enchants.keySet().contains(enchantments.getOrThrow(enchantment))) {
211
                                        String id = encMap.get(enchantment);
212
                                        int level = enchants.getLevel(enchantments.getOrThrow(enchantment));
213
                                        String encName = id + level;
214
215
                                        if (font.getValue() == Font.Fancy) {
216
                                            FontRenderers.sf_bold.drawString(context.pose(), encName, posX - 50 + item_offset, (float) posY - 45 + enchantmentY, -1);
217
                                        } else {
218
                                            context.pose().pushMatrix();
219
                                            context.pose().translate((float) ((posX - 50f + item_offset)), (float) ((posY - 45f + enchantmentY)));
220
                                            context.text(mc.font, encName, 0, 0, -1, false);
221
                                            context.pose().popMatrix();
222
                                        }
223
                                        enchantmentY -= 8;
224
                                        if (maxEnchantY > enchantmentY)
225
                                            maxEnchantY = enchantmentY;
226
                                    }
227
                                }
228
                            }
229
                        }
230
                    }
231
                    item_offset += 18f;
232
                }
233
234
                Color color = Managers.FRIEND.isFriend(ent) ? fillColorF.getValue().getColorObject() : fillColorA.getValue().getColorObject();
235
236
                OutlineColor cl = Managers.FRIEND.isFriend(ent) ? friendOutline.getValue() : outline.getValue();
237
238
                if (cl == OutlineColor.New)
239
                    Render2DEngine.drawRectWithOutline(context.pose(), tagX - 2, (float) (posY - 13f), textWidth + 4, 11, color, outlineColor.getValue().getColorObject());
240
                else
241
                    Render2DEngine.drawRect(context.pose(), tagX - 2, (float) (posY - 13f), textWidth + 4, 11, color);
242
243
                if (Managers.TELEMETRY.getOnlinePlayers().contains(ent.getGameProfile().name())) {
244
                    Render2DEngine.drawRect(context.pose(), tagX - 14, (float) (posY - 13f), 12, 11, color.brighter().brighter());
245
                    RenderSystem.enableBlend();
246
                    RenderSystem.blendFunc(GlStateManager.SrcFactor.SRC_ALPHA, GlStateManager.DstFactor.ONE);
247
                    Color lColor = HudEditor.getColor(0);
248
                    RenderSystem.setShaderColor(lColor.getRed() / 255f, lColor.getGreen() / 255f, lColor.getBlue() / 255f, 1f);
249
                    RenderSystem.setShaderTexture(0, TextureStorage.miniLogo);
250
                    Render2DEngine.renderTexture(context.pose(), tagX - 13, (float) (posY - 12.5f), 10, 10, 0, 0, 256, 256, 256, 256);
251
                    RenderSystem.setShaderColor(1f, 1f, 1f, 1f);
252
                    RenderSystem.disableBlend();
253
                }
254
255
                switch (cl) {
256
                    case None, New -> {
257
258
                    }
259
                    case Sync -> {
260
                        Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 14f), textWidth + 6, 1, HudEditor.getColor(270));
261
                        Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 3f), textWidth + 6, 1, HudEditor.getColor(0));
262
                        Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 14f), 1, 11, HudEditor.getColor(180));
263
                        Render2DEngine.drawRect(context.pose(), tagX + textWidth + 2, (float) (posY - 14f), 1, 11, HudEditor.getColor(90));
264
                    }
265
                    case Custom -> {
266
                        Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 14f), textWidth + 6, 1, Managers.FRIEND.isFriend(ent) ? friendOutlineColor.getValue().getColorObject() : outlineColor.getValue().getColorObject());
267
                        Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 3f), textWidth + 6, 1, Managers.FRIEND.isFriend(ent) ? friendOutlineColor.getValue().getColorObject() : outlineColor.getValue().getColorObject());
268
                        Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 14f), 1, 11, Managers.FRIEND.isFriend(ent) ? friendOutlineColor.getValue().getColorObject() : outlineColor.getValue().getColorObject());
269
                        Render2DEngine.drawRect(context.pose(), tagX + textWidth + 2, (float) (posY - 14f), 1, 11, Managers.FRIEND.isFriend(ent) ? friendOutlineColor.getValue().getColorObject() : outlineColor.getValue().getColorObject());
270
                    }
271
                }
272
273
274
                if (font.getValue() == Font.Fancy) {
275
                    FontRenderers.sf_bold.drawString(context.pose(), final_string, tagX, (float) posY - 10, -1);
276
                } else {
277
                    context.pose().pushMatrix();
278
                    context.pose().translate((float) (tagX), (float) (((float) posY - 11)));
279
                    context.text(mc.font, final_string, 0, 0, -1, false);
280
                    context.pose().popMatrix();
281
                }
282
283
                if (!health.is(Health.Number)) {
284
                    int i = Mth.ceil(ent.getHealth());
285
                    float f = (float) ent.getAttributeValue(Attributes.MAX_HEALTH);
286
                    int p = Mth.ceil(ent.getAbsorptionAmount());
287
                    context.pose().pushMatrix();
288
                    context.pose().translate((float) (posX - 44), (float) (posY));
289
                    context.pose().scale(1.1f, 1.1f);
290
                    renderHealthBar(context, ent, f, i, p);
291
                    context.pose().popMatrix();
292
                }
293
294
                if (potions.getValue())
295
                    renderStatusEffectOverlay(context, (float) posX, (float) (posY + maxEnchantY - 60), ent);
296
297
                Item handItem = ent.getMainHandItem().getItem();
298
299
                if (shulkers.getValue())
300
                    renderShulkerToolTip(context, (int) posX - 90, (int) posY - 120, (handItem instanceof BlockItem bi) && (bi.getBlock() instanceof ShulkerBoxBlock) ? ent.getMainHandItem() : ent.getOffhandItem());
301
                context.pose().popMatrix();
302
            }
303
        }
304
305
        if (spawners.getValue()) drawSpawnerNameTag(context);
306
        if (entityOwner.getValue()) drawEntityOwner(context);
307
    }
308
309
    private void drawSpawnerNameTag(GuiGraphicsExtractor context) {
310
        for (BlockEntity blockEntity : StorageEsp.getBlockEntities()) {
311
            if (blockEntity instanceof SpawnerBlockEntity spawner) {
312
                Vec3 vector = new Vec3(spawner.getBlockPos().getX() + 0.5, spawner.getBlockPos().getY() + 1.5, spawner.getBlockPos().getZ() + 0.5);
313
                Vector4d position = null;
314
                vector = Render3DEngine.worldSpaceToScreenSpace(new Vec3(vector.x, vector.y, vector.z));
315
                if (vector.z > 0 && vector.z < 1) {
316
                    position = new Vector4d(vector.x, vector.y, vector.z, 0);
317
                    position.x = Math.min(vector.x, position.x);
318
                    position.y = Math.min(vector.y, position.y);
319
                    position.z = Math.max(vector.x, position.z);
320
                }
321
                if (spawner.getSpawner() == null || spawner.getSpawner().getOrCreateDisplayEntity(mc.level, spawner.getBlockPos()) == null)
322
                    continue;
323
                String final_string = spawner.getSpawner().getOrCreateDisplayEntity(mc.level, spawner.getBlockPos()).getName().getString() + " " + String.format("%.1f", ((float) spawner.getSpawner().spawnDelay / 20f)) + "s";
324
325
                if (spawner.getSpawner().getSpin() == spawner.getSpawner().getOSpin() && spawner.getSpawner().getSpin() == 0f && (float) spawner.getSpawner().spawnDelay / 20f == 1f)
326
                    final_string = spawner.getSpawner().getOrCreateDisplayEntity(mc.level, spawner.getBlockPos()).getName().getString() + " loot!";
327
328
329
                if (position != null) {
330
                    double posX = position.x;
331
                    double posY = position.y;
332
                    double endPosX = position.z;
333
334
                    float diff = (float) (endPosX - posX) / 2;
335
                    float textWidth = (FontRenderers.sf_bold.getStringWidth(final_string) * 1);
336
                    float tagX = (float) ((posX + diff - textWidth / 2) * 1);
337
338
                    Render2DEngine.drawRect(context.pose(), tagX - 2, (float) (posY - 13f), textWidth + 4, 11, fillColorA.getValue().getColorObject());
339
340
                    switch (outline.getValue()) {
341
                        case None -> {
342
343
                        }
344
                        case Sync -> {
345
                            Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 14f), textWidth + 6, 1, HudEditor.getColor(270));
346
                            Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 3f), textWidth + 6, 1, HudEditor.getColor(0));
347
                            Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 14f), 1, 11, HudEditor.getColor(180));
348
                            Render2DEngine.drawRect(context.pose(), tagX + textWidth + 2, (float) (posY - 14f), 1, 11, HudEditor.getColor(90));
349
                        }
350
                        case Custom -> {
351
                            Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 14f), textWidth + 6, 1, outlineColor.getValue().getColorObject());
352
                            Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 3f), textWidth + 6, 1, outlineColor.getValue().getColorObject());
353
                            Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 14f), 1, 11, outlineColor.getValue().getColorObject());
354
                            Render2DEngine.drawRect(context.pose(), tagX + textWidth + 2, (float) (posY - 14f), 1, 11, outlineColor.getValue().getColorObject());
355
                        }
356
                    }
357
358
359
                    FontRenderers.sf_bold.drawString(context.pose(), final_string, tagX, (float) posY - 10, -1);
360
                }
361
            }
362
        }
363
    }
364
365
    public void drawEntityOwner(GuiGraphicsExtractor context) {
366
        for (Entity ent : mc.level.entitiesForRendering()) {
367
            String ownerName = "";
368
            if (ent instanceof Projectile pe) {
369
                if (pe.getOwner() != null) ownerName = pe.getOwner().getDisplayName().getString();
370
            } else if (ent instanceof Horse he) {
371
                if (he.getOwner() != null) ownerName = he.getOwner().getDisplayName().getString();
372
            } else if (ent instanceof TamableAnimal te && te.isTame() && te.getOwner() != null) {
373
                ownerName = te.getOwner().getDisplayName().getString();
374
            } else continue;
375
376
            String final_string = "Owned by " + ownerName;
377
            double x = ent.xo + (ent.getX() - ent.xo) * Render3DEngine.getTickDelta();
378
            double y = ent.yo + (ent.getY() - ent.yo) * Render3DEngine.getTickDelta();
379
            double z = ent.zo + (ent.getZ() - ent.zo) * Render3DEngine.getTickDelta();
380
            Vec3 vector = new Vec3(x, y + 2, z);
381
            Vector4d position = null;
382
            vector = Render3DEngine.worldSpaceToScreenSpace(new Vec3(vector.x, vector.y, vector.z));
383
            if (vector.z > 0 && vector.z < 1) {
384
                position = new Vector4d(vector.x, vector.y, vector.z, 0);
385
                position.x = Math.min(vector.x, position.x);
386
                position.y = Math.min(vector.y, position.y);
387
                position.z = Math.max(vector.x, position.z);
388
            }
389
390
            if (position != null) {
391
                double posX = position.x;
392
                double posY = position.y;
393
                double endPosX = position.z;
394
395
                float diff = (float) (endPosX - posX) / 2;
396
                float textWidth = (FontRenderers.sf_bold.getStringWidth(final_string) * 1);
397
                float tagX = (float) ((posX + diff - textWidth / 2) * 1);
398
399
                Render2DEngine.drawRect(context.pose(), tagX - 2, (float) (posY - 13f), textWidth + 4, 11, fillColorA.getValue().getColorObject());
400
401
                switch (outline.getValue()) {
402
                    case None -> {
403
404
                    }
405
                    case Sync -> {
406
                        Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 14f), textWidth + 6, 1, HudEditor.getColor(270));
407
                        Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 3f), textWidth + 6, 1, HudEditor.getColor(0));
408
                        Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 14f), 1, 11, HudEditor.getColor(180));
409
                        Render2DEngine.drawRect(context.pose(), tagX + textWidth + 2, (float) (posY - 14f), 1, 11, HudEditor.getColor(90));
410
                    }
411
                    case Custom -> {
412
                        Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 14f), textWidth + 6, 1, outlineColor.getValue().getColorObject());
413
                        Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 3f), textWidth + 6, 1, outlineColor.getValue().getColorObject());
414
                        Render2DEngine.drawRect(context.pose(), tagX - 3, (float) (posY - 14f), 1, 11, outlineColor.getValue().getColorObject());
415
                        Render2DEngine.drawRect(context.pose(), tagX + textWidth + 2, (float) (posY - 14f), 1, 11, outlineColor.getValue().getColorObject());
416
                    }
417
                }
418
                FontRenderers.sf_bold.drawString(context.pose(), final_string, tagX, (float) posY - 10, -1);
419
            }
420
        }
421
    }
422
423
    public static int getEntityPing(Player entity) {
424
        if (mc.getConnection() == null) return 0;
425
        PlayerInfo playerListEntry = mc.getConnection().getPlayerInfo(entity.getUUID());
426
        if (playerListEntry == null) return 0;
427
        return playerListEntry.getLatency();
428
    }
429
430
    public static GameType getEntityGamemode(Player entity) {
431
        if (entity == null) return null;
432
        PlayerInfo playerListEntry = mc.getConnection().getPlayerInfo(entity.getUUID());
433
        return playerListEntry == null ? null : playerListEntry.getGameMode();
434
    }
435
436
    private String translateGamemode(GameType gamemode) {
437
        if (gamemode == null) return "[BOT]";
438
        return switch (gamemode) {
439
            case SURVIVAL -> "[S]";
440
            case CREATIVE -> "[C]";
441
            case SPECTATOR -> "[SP]";
442
            case ADVENTURE -> "[A]";
443
        };
444
    }
445
446
    public float getHealth(Player ent) {
447
        // Первый в комьюнити хп резольвер. Правда, еж?
448
        if ((mc.getConnection() != null && mc.getConnection().getServerData() != null && mc.getConnection().getServerData().ip.contains("funtime") || funtimeHp.getValue())) {
449
            Objective scoreBoard = null;
450
            String resolvedHp = "";
451
            if ((ent.level().getScoreboard()).getDisplayObjective(DisplaySlot.BELOW_NAME) != null) {
452
                scoreBoard = (ent.level().getScoreboard()).getDisplayObjective(DisplaySlot.BELOW_NAME);
453
                if (scoreBoard != null) {
454
                    ReadOnlyScoreInfo readableScoreboardScore = ent.level().getScoreboard().getPlayerScoreInfo(ent, scoreBoard);
455
                    MutableComponent text2 = readableScoreboardScore.formatValue( scoreBoard.numberFormatOrDefault(StyledFormat.NO_STYLE));
456
                    resolvedHp = text2.getString();
457
                }
458
            }
459
            float numValue = 0;
460
            try {
461
                numValue = Float.parseFloat(resolvedHp);
462
            } catch (NumberFormatException ignored) {
463
            }
464
            return numValue;
465
        } else return ent.getHealth() + ent.getAbsorptionAmount();
466
    }
467
468
    private void renderHealthBar(GuiGraphicsExtractor context, Player player, float maxHealth, int lastHealth, int absorption) {
469
        int i = Mth.ceil((double) maxHealth / 2.0);
470
        int j = Mth.ceil((double) absorption / 2.0);
471
        int k = i * 2;
472
        int cont = 0;
473
474
        for (int l = i + j - 1; l >= 0; --l) {
475
            int n = l % 10;
476
            int o = n * 8;
477
478
            if (cont < 10) {
479
                drawHeart(context, HeartType.CONTAINER, o, false, player);
480
                cont++;
481
            }
482
483
            int q = l * 2;
484
            if (q < lastHealth) {
485
                drawHeart(context, HeartType.NORMAL, o, q + 1 == lastHealth, player);
486
            }
487
488
            if (l >= i) {
489
                int r = q - k;
490
                if (q - k < absorption) {
491
                    context.pose().pushMatrix();
492
                    context.pose().translate((float) (0), (float) (0));
493
                    drawHeart(context, HeartType.ABSORBING, o, r + 1 == absorption, player);
494
                    context.pose().popMatrix();
495
                }
496
            }
497
        }
498
499
    }
500
501
    private void drawHeart(GuiGraphicsExtractor context, HeartType type, int x, boolean half, Player player) {
502
        if (health.is(Health.Dots)) {
503
504
            Color color = Managers.FRIEND.isFriend(player) ? fillColorF.getValue().getColorObject() : fillColorA.getValue().getColorObject();
505
            if (type == HeartType.CONTAINER) {
506
                Render2DEngine.drawRect(context.pose(), x, 0, 7, 3, color);
507
            } else if (type == HeartType.NORMAL) {
508
                if (half) {
509
                    Render2DEngine.drawRect(context.pose(), x, 0, 3, 3, getHealthColor2(player.getHealth() + player.getAbsorptionAmount()));
510
                    Render2DEngine.drawRect(context.pose(), x + 3, 0, 4, 3, color);
511
                } else {
512
                    Render2DEngine.drawRect(context.pose(), x, 0, 7, 3, getHealthColor2(player.getHealth() + player.getAbsorptionAmount()));
513
                }
514
            }
515
        } else context.blitSprite(net.minecraft.client.renderer.RenderPipelines.GUI_TEXTURED, type.getTexture(half), x, 0, 9, 9);
516
    }
517
518
    private enum HeartType {
519
        CONTAINER(Identifier.parse("hud/heart/container"), Identifier.parse("hud/heart/container")), NORMAL(Identifier.parse("hud/heart/full"), Identifier.parse("hud/heart/half")), ABSORBING(Identifier.parse("hud/heart/absorbing_full"), Identifier.parse("hud/heart/absorbing_half"));
520
521
        private final Identifier fullTexture;
522
        private final Identifier halfTexture;
523
524
        HeartType(Identifier fullTexture, Identifier halfTexture) {
525
            this.fullTexture = fullTexture;
526
            this.halfTexture = halfTexture;
527
        }
528
529
        public Identifier getTexture(boolean half) {
530
            return half ? halfTexture : fullTexture;
531
        }
532
    }
533
534
    public @NotNull String getHealthColor(float health) {
535
        if (health <= 15 && health > 7) return ChatFormatting.YELLOW + "";
536
        if (health > 15) return ChatFormatting.GREEN + "";
537
        return ChatFormatting.RED + "";
538
    }
539
540
    public @NotNull String getPingColor(int ping) {
541
        if (ping <= 60) return ChatFormatting.GREEN + "";
542
        if (ping > 60 && ping < 120) return ChatFormatting.YELLOW + "";
543
        return ChatFormatting.RED + "";
544
    }
545
546
    private @NotNull Color getHealthColor2(float health) {
547
        if (health <= 15 && health > 7) return Color.YELLOW;
548
        if (health > 15) return Color.GREEN;
549
        return Color.RED;
550
    }
551
552
    public static float round2(float value) {
553
        if (Float.isNaN(value) || Float.isInfinite(value)) return 1f;
554
        BigDecimal bd = new BigDecimal(value);
555
        bd = bd.setScale(1, RoundingMode.HALF_UP);
556
        return bd.floatValue();
557
    }
558
559
    private void renderStatusEffectOverlay(GuiGraphicsExtractor context, float x, float y, Player player) {
560
        ArrayList<MobEffectInstance> effects = new ArrayList<>(player.getActiveEffects());
561
        if (effects.isEmpty()) return;
562
        x += effects.size() * 12.5f;
563
        RenderSystem.enableBlend();
564
        RenderSystem.defaultBlendFunc();
565
        for (MobEffectInstance statusEffectInstance : Ordering.natural().reverse().sortedCopy(effects)) {
566
            x -= 25;
567
            String power = "";
568
            switch (statusEffectInstance.getAmplifier()) {
569
                case 0 -> power = "I";
570
                case 1 -> power = "II";
571
                case 2 -> power = "III";
572
                case 3 -> power = "IV";
573
                case 4 -> power = "V";
574
            }
575
576
            context.pose().pushMatrix();
577
            context.pose().translate((float) (x), (float) (y));
578
            context.blitSprite(net.minecraft.client.renderer.RenderPipelines.GUI_TEXTURED, statusEffectInstance.getEffect().unwrapKey().orElseThrow().identifier(), 0, 0, 18, 18);
579
            FontRenderers.sf_bold_mini.drawCenteredString(context.pose(), PotionHud.getDuration(statusEffectInstance), 9, -8, -1);
580
            FontRenderers.categories.drawCenteredString(context.pose(), power, 9, -16, -1);
581
            context.pose().popMatrix();
582
583
        }
584
        RenderSystem.disableBlend();
585
    }
586
587
    public boolean renderShulkerToolTip(GuiGraphicsExtractor context, int offsetX, int offsetY, ItemStack stack) {
588
        try {
589
            ItemContainerContents compoundTag = stack.get(DataComponents.CONTAINER);
590
            if (compoundTag == null) return false;
591
592
            float[] colors = new float[]{1F, 1F, 1F};
593
            Item focusedItem = stack.getItem();
594
            if (focusedItem instanceof BlockItem bi && bi.getBlock() instanceof ShulkerBoxBlock) {
595
                try {
596
                    Color c = new Color(Objects.requireNonNull(((ShulkerBoxBlock) bi.getBlock()).getColor()).getTextureDiffuseColor());
597
                    colors = new float[]{c.getRed() / 255f, c.getGreen() / 255f, c.getRed() / 255f, c.getAlpha() / 255f};
598
                } catch (NullPointerException npe) {
599
                    colors = new float[]{1F, 1F, 1F};
600
                }
601
            } else {
602
                return false;
603
            }
604
            draw(context, compoundTag.allItemsCopyStream().toList(), offsetX, offsetY, colors);
605
        } catch (Exception ignore) {
606
            return false;
607
        }
608
        return true;
609
    }
610
611
    private void draw(GuiGraphicsExtractor context, List<ItemStack> itemStacks, int offsetX, int offsetY, float[] colors) {
612
        RenderSystem.disableDepthTest();
613
        GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT);
614
615
        offsetX += 8;
616
        offsetY -= 82;
617
618
        drawBackground(context, offsetX, offsetY, colors);
619
620
        RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
621
        int row = 0;
622
        int i = 0;
623
        for (ItemStack itemStack : itemStacks) {
624
            context.item(itemStack, offsetX + 8 + i * 18, offsetY + 7 + row * 18);
625
            context.itemDecorations(mc.font, itemStack, offsetX + 8 + i * 18, offsetY + 7 + row * 18);
626
            i++;
627
            if (i >= 9) {
628
                i = 0;
629
                row++;
630
            }
631
        }
632
        RenderSystem.enableDepthTest();
633
    }
634
635
    private void drawBackground(GuiGraphicsExtractor context, int x, int y, float[] colors) {
636
        RenderSystem.disableBlend();
637
        RenderSystem.setShaderColor(colors[0], colors[1], colors[2], 1F);
638
        RenderSystem.texParameter(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
639
        RenderSystem.texParameter(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
640
        context.blit(net.minecraft.client.renderer.RenderPipelines.GUI_TEXTURED, TextureStorage.container, x, y, 0, 0, 176, 67, 176, 67);
641
        RenderSystem.enableBlend();
642
    }
643
644
    public enum Font {
645
        Fancy, Fast
646
    }
647
648
    public enum Armor {
649
        None, Full, Durability
650
    }
651
652
    public enum Health {
653
        Number, Hearts, Dots
654
    }
655
656
    private enum OutlineColor {
657
        Sync, Custom, None, New
658
    }
659
}
660
OfflineClientRENDERsrc/main/java/com/jellypudding/offlineclient/modules/render/Nametags.javaJava · 498 lines · 21.9 KB

Shows health and ping and gear above players and names above other things.

SettingsScaleRangeTag limitSelfIgnore friendsIgnore botsDisplay nameGame modeHealthPingPing by latencyPing colourDistanceDistance colour modeDistance colourHeld itemsArmourItem spacingIgnore empty slotsDurabilityItem countEnchantmentsShown enchantmentsEnchantment positionEnchantment lettersEnchantment scaleName colourGame mode colourBackground colourBackground opacity
Nametags.javaJava · Minecraft 26.2 · 498 lines · 21.9 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.render;
2
3
import com.jellypudding.offlineclient.event.Subscribe;
4
import com.jellypudding.offlineclient.event.events.Render2DEvent;
5
import com.jellypudding.offlineclient.module.Category;
6
import com.jellypudding.offlineclient.module.Module;
7
import com.jellypudding.offlineclient.render.WorldToScreen;
8
import com.jellypudding.offlineclient.setting.BoolSetting;
9
import com.jellypudding.offlineclient.setting.ChoiceListSetting;
10
import com.jellypudding.offlineclient.setting.ColorSetting;
11
import com.jellypudding.offlineclient.setting.EnumSetting;
12
import com.jellypudding.offlineclient.setting.NumberSetting;
13
import com.jellypudding.offlineclient.util.ColorUtil;
14
import com.jellypudding.offlineclient.util.EntityFilter;
15
import com.jellypudding.offlineclient.util.EntityUtil;
16
import com.jellypudding.offlineclient.util.ItemUtil;
17
import com.jellypudding.offlineclient.util.Modules;
18
import com.jellypudding.offlineclient.util.RenderUtil;
19
import net.minecraft.client.gui.Font;
20
import net.minecraft.client.gui.GuiGraphicsExtractor;
21
import net.minecraft.client.multiplayer.PlayerInfo;
22
import net.minecraft.core.Holder;
23
import net.minecraft.tags.EnchantmentTags;
24
import net.minecraft.world.entity.Entity;
25
import net.minecraft.world.entity.EntityTypes;
26
import net.minecraft.world.entity.EquipmentSlot;
27
import net.minecraft.world.entity.LivingEntity;
28
import net.minecraft.world.entity.decoration.ItemFrame;
29
import net.minecraft.world.entity.item.ItemEntity;
30
import net.minecraft.world.entity.item.PrimedTnt;
31
import net.minecraft.world.entity.player.Player;
32
import net.minecraft.world.entity.vehicle.minecart.MinecartTNT;
33
import net.minecraft.world.item.ItemStack;
34
import net.minecraft.world.item.enchantment.Enchantment;
35
import net.minecraft.world.item.enchantment.EnchantmentHelper;
36
import net.minecraft.world.item.enchantment.ItemEnchantments;
37
import net.minecraft.world.level.GameType;
38
import net.minecraft.world.phys.Vec3;
39
import org.joml.Matrix3x2fStack;
40
41
import java.util.ArrayList;
42
import java.util.List;
43
44
// Drawn on the HUD at the projected head position.
45
public final class Nametags extends Module {
46
47
    public enum Durability { NONE, BAR, NUMBER, PERCENT }
48
49
    public enum EnchantPosition { ABOVE, ON_TOP }
50
51
    public enum DistanceColor { GRADIENT, FLAT }
52
53
    private static final int ITEM_SIZE = 16;
54
    private static final int GOLD = 0xFFE8B923;
55
    private static final int RED = 0xFFFF4040;
56
    private static final int TICKS_PER_SECOND = 20;
57
    private static final int TICKS_PER_MINUTE = TICKS_PER_SECOND * 60;
58
    private static final int TICKS_PER_HOUR = TICKS_PER_MINUTE * 60;
59
60
    // The order the six item slots are drawn in.
61
    private static final EquipmentSlot[] SLOTS = {
62
        EquipmentSlot.MAINHAND, EquipmentSlot.HEAD, EquipmentSlot.CHEST,
63
        EquipmentSlot.LEGS, EquipmentSlot.FEET, EquipmentSlot.OFFHAND
64
    };
65
66
    private static final List<String> DEFAULT_ENCHANTMENTS = List.of(
67
        "minecraft:protection", "minecraft:blast_protection",
68
        "minecraft:fire_protection", "minecraft:projectile_protection");
69
70
    private record Tag(Entity entity, Vec3 screen, double distance) {
71
    }
72
73
    private record Enchant(String text, int color) {
74
    }
75
76
    private final NumberSetting scale = new NumberSetting("Scale",
77
        "Size of the tags.", 1, 0.5, 3, 0.1).min(0.1);
78
    private final NumberSetting range = new NumberSetting("Range",
79
        "Furthest entity to tag.", 128, 16, 256, 8, " blocks").min(1);
80
    private final NumberSetting limit = new NumberSetting("Tag limit",
81
        "How many of the nearest entities get a tag.", 50, 1, 100, 1).min(1);
82
    private final EntityFilter filter = new EntityFilter("Tag", "tagged", true,
83
        EntityFilter.Pick.NONE, EntityFilter.Pick.ALL,
84
        List.of(EntityTypes.ITEM_FRAME, EntityTypes.GLOW_ITEM_FRAME));
85
    private final BoolSetting self = new BoolSetting("Self",
86
        "Tag yourself whilst in third person or Freecam.", true);
87
    private final BoolSetting ignoreFriends = new BoolSetting("Ignore friends",
88
        "Friends get no tag.", false);
89
    private final BoolSetting ignoreBots = new BoolSetting("Ignore bots",
90
        "Players missing from the tab list get no tag. Off labels them as bots.", true);
91
    private final BoolSetting displayName = new BoolSetting("Display name",
92
        "Show the server display name with any team prefix instead of the account name.", false);
93
    private final BoolSetting gameMode = new BoolSetting("Game mode",
94
        "Put the player's game mode in front of the name.", false);
95
    private final BoolSetting health = new BoolSetting("Health",
96
        "Show hearts left including absorption.", true);
97
    private final BoolSetting ping = new BoolSetting("Ping",
98
        "Show the player's latency.", true);
99
    private final BoolSetting pingByLatency = new BoolSetting("Ping by latency",
100
        "Colour the ping green then amber then red as it climbs.", true).under(ping);
101
    private final ColorSetting pingColor = new ColorSetting("Ping colour",
102
        "Colour of the ping text.", 180, 0.88f, 0.67f, false).under(ping, () -> ping.isOn() && !pingByLatency.isOn());
103
    private final BoolSetting distance = new BoolSetting("Distance",
104
        "Show how far away the player is.", false);
105
    private final EnumSetting<DistanceColor> distanceColor = new EnumSetting<>("Distance colour mode",
106
        "How the distance text is coloured.", DistanceColor.GRADIENT)
107
        .describe(DistanceColor.GRADIENT, "Red up close through to green far away.")
108
        .describe(DistanceColor.FLAT, "One colour picked below.")
109
        .under(distance);
110
    private final ColorSetting flatDistanceColor = new ColorSetting("Distance colour",
111
        "Colour of the distance text.", 0, 0f, 0.59f, false)
112
        .under(distance, () -> distance.isOn() && distanceColor.is(DistanceColor.FLAT));
113
    private final BoolSetting items = new BoolSetting("Held items",
114
        "Show what they hold in each hand.", true);
115
    private final BoolSetting armor = new BoolSetting("Armour",
116
        "Show their armour next to the held items.", true);
117
    private final NumberSetting itemSpacing = new NumberSetting("Item spacing",
118
        "Gap in pixels between the item icons.", 2, 0, 10, 1, " px");
119
    private final BoolSetting ignoreEmpty = new BoolSetting("Ignore empty slots",
120
        "Empty slots take no room. Off keeps every icon in a fixed column.", true);
121
    private final EnumSetting<Durability> durability = new EnumSetting<>("Durability",
122
        "How the wear of each item is shown.", Durability.BAR)
123
        .describe(Durability.NONE, "Nothing.")
124
        .describe(Durability.BAR, "The usual bar under the icon.")
125
        .describe(Durability.NUMBER, "The points left written over the icon.")
126
        .describe(Durability.PERCENT, "The share left written over the icon.");
127
    private final BoolSetting showCount = new BoolSetting("Item count",
128
        "Show how many are in a dropped stack.", true);
129
    private final BoolSetting enchantments = new BoolSetting("Enchantments",
130
        "Write the enchantments of each item by its icon.", false);
131
    private final ChoiceListSetting shownEnchantments = new ChoiceListSetting("Shown enchantments",
132
        "Which enchantments are written. Join a world to fill the list.", ItemUtil::enchantmentIds,
133
        DEFAULT_ENCHANTMENTS).under(enchantments);
134
    private final EnumSetting<EnchantPosition> enchantPosition = new EnumSetting<>("Enchantment position",
135
        "Where the enchantment text sits.", EnchantPosition.ABOVE)
136
        .describe(EnchantPosition.ABOVE, "Above the row of icons.")
137
        .describe(EnchantPosition.ON_TOP, "Over each icon.")
138
        .under(enchantments);
139
    private final NumberSetting enchantLetters = new NumberSetting("Enchantment letters",
140
        "How many letters of each enchantment name are kept.", 3, 1, 5, 1).min(1).under(enchantments);
141
    private final NumberSetting enchantScale = new NumberSetting("Enchantment scale",
142
        "Size of the enchantment text.", 1, 0.1, 2, 0.1).min(0.1).under(enchantments);
143
    private final ColorSetting nameColor = new ColorSetting("Name colour",
144
        "Colour of the name text.", 0, 0f, 1f, false);
145
    private final ColorSetting gameModeColor = new ColorSetting("Game mode colour",
146
        "Colour of the game mode letters.", 46, 0.85f, 0.91f, false).under(gameMode);
147
    private final ColorSetting background = new ColorSetting("Background colour",
148
        "Colour behind the tag.", 0, 0f, 0f, false);
149
    private final NumberSetting backgroundOpacity = new NumberSetting("Background opacity",
150
        "How solid the background is.", 55, 0, 100, 5, "%");
151
152
    public Nametags() {
153
        super("Nametags", "Shows health and ping and gear above players and names above other things.",
154
            Category.RENDER);
155
        addSettings(scale, range, limit);
156
        addSettings(filter.settings());
157
        addSettings(self, ignoreFriends, ignoreBots, displayName, gameMode, health, ping, pingByLatency,
158
            pingColor, distance, distanceColor, flatDistanceColor, items, armor, itemSpacing, ignoreEmpty,
159
            durability, showCount, enchantments, shownEnchantments, enchantPosition, enchantLetters,
160
            enchantScale, nameColor, gameModeColor, background, backgroundOpacity);
161
        searchTags("name tags", "player info");
162
    }
163
164
    @Subscribe
165
    private void onRender2D(Render2DEvent event) {
166
        if (!inGame() || !WorldToScreen.update()) {
167
            return;
168
        }
169
        float partialTicks = event.getPartialTicks();
170
        Vec3 camera = WorldToScreen.cameraPos();
171
        List<Tag> tags = new ArrayList<>();
172
173
        for (Entity entity : mc.level.entitiesForRendering()) {
174
            if (!wanted(entity)) {
175
                continue;
176
            }
177
            Vec3 feet = entity.getPosition(partialTicks);
178
            double dist = camera.distanceTo(feet);
179
            if (dist > range.getValue()) {
180
                continue;
181
            }
182
            Vec3 screen = WorldToScreen.project(feet.add(0, tagHeight(entity), 0));
183
            if (screen != null) {
184
                tags.add(new Tag(entity, screen, dist));
185
            }
186
        }
187
188
        tags.sort((a, b) -> Double.compare(a.distance(), b.distance()));
189
        if (tags.size() > limit.getInt()) {
190
            tags = tags.subList(0, limit.getInt());
191
        }
192
        // Far tags draw first. Near ones sit on top.
193
        for (int i = tags.size() - 1; i >= 0; i--) {
194
            drawTag(event.getContext(), tags.get(i));
195
        }
196
    }
197
198
    private boolean wanted(Entity entity) {
199
        if (entity == mc.player) {
200
            return filter.wantsPlayers() && showSelf();
201
        }
202
        if (entity instanceof Player player) {
203
            if (!filter.matches(player)) {
204
                return false;
205
            }
206
            if (ignoreFriends.isOn() && EntityUtil.isFriend(player)) {
207
                return false;
208
            }
209
            return !ignoreBots.isOn() || tabEntry(player) != null;
210
        }
211
        return filter.matches(entity);
212
    }
213
214
    private boolean showSelf() {
215
        if (!self.isOn()) {
216
            return false;
217
        }
218
        if (Modules.enabled(Freecam.class)) {
219
            return true;
220
        }
221
        return !mc.options.getCameraType().isFirstPerson();
222
    }
223
224
    // Items sit low and their tag hugs them. Everything else gets a little headroom.
225
    private static double tagHeight(Entity entity) {
226
        boolean item = entity instanceof ItemEntity || entity instanceof ItemFrame;
227
        return entity.getEyeHeight() + (item ? 0.2 : 0.5);
228
    }
229
230
    private void drawTag(GuiGraphicsExtractor context, Tag tag) {
231
        // Shrink with distance down to half size.
232
        float factor = (float) (scale.getValue() * Math.clamp(1 - tag.distance() / 100.0, 0.5, 1));
233
        switch (tag.entity()) {
234
            case Player player -> drawPlayer(context, tag, player, factor);
235
            case ItemEntity item -> drawItem(context, tag, item.getItem(), factor);
236
            case ItemFrame frame -> drawItem(context, tag, frame.getItem(), factor);
237
            case PrimedTnt tnt -> drawText(context, tag, fuseText(tnt.getFuse()), factor);
238
            case MinecartTNT cart -> drawText(context, tag, fuseText(cart.getFuse()), factor);
239
            case LivingEntity living -> drawLiving(context, tag, living, factor);
240
            default -> drawText(context, tag, typeName(tag.entity()), factor);
241
        }
242
    }
243
244
    private void drawPlayer(GuiGraphicsExtractor context, Tag tag, Player player, float factor) {
245
        List<String> parts = new ArrayList<>();
246
        List<Integer> colors = new ArrayList<>();
247
248
        if (gameMode.isOn()) {
249
            parts.add("[" + gameModeText(player) + "] ");
250
            colors.add(gameModeColor.getColor());
251
        }
252
        parts.add(nameText(player));
253
        colors.add(playerNameColor(player));
254
255
        if (health.isOn()) {
256
            addHealth(parts, colors, player);
257
        }
258
        if (ping.isOn()) {
259
            int latency = latencyOf(player);
260
            if (latency >= 0) {
261
                parts.add(" " + latency + "ms");
262
                colors.add(pingByLatency.isOn() ? ColorUtil.ping(latency) : pingColor.getColor());
263
            }
264
        }
265
        if (distance.isOn() && (player != mc.player || Modules.enabled(Freecam.class))) {
266
            parts.add(String.format(" %.1fm", tag.distance()));
267
            colors.add(distanceColor.is(DistanceColor.FLAT)
268
                ? flatDistanceColor.getColor() : EntityUtil.distanceColor(player));
269
        }
270
271
        label(context, tag, factor, parts, colors);
272
        drawGear(context, tag, player, factor);
273
    }
274
275
    private void drawLiving(GuiGraphicsExtractor context, Tag tag, LivingEntity living, float factor) {
276
        List<String> parts = new ArrayList<>();
277
        List<Integer> colors = new ArrayList<>();
278
        parts.add(typeName(living));
279
        colors.add(nameColor.getColor());
280
        addHealth(parts, colors, living);
281
        label(context, tag, factor, parts, colors);
282
    }
283
284
    private void drawItem(GuiGraphicsExtractor context, Tag tag, ItemStack stack, float factor) {
285
        if (stack.isEmpty()) {
286
            return;
287
        }
288
        List<String> parts = new ArrayList<>();
289
        List<Integer> colors = new ArrayList<>();
290
        parts.add(stack.getHoverName().getString());
291
        colors.add(nameColor.getColor());
292
        if (showCount.isOn()) {
293
            parts.add(" x" + stack.getCount());
294
            colors.add(GOLD);
295
        }
296
        label(context, tag, factor, parts, colors);
297
    }
298
299
    private void drawText(GuiGraphicsExtractor context, Tag tag, String text, float factor) {
300
        label(context, tag, factor, List.of(text), List.of(nameColor.getColor()));
301
    }
302
303
    private void label(GuiGraphicsExtractor context, Tag tag, float factor,
304
                       List<String> parts, List<Integer> colors) {
305
        RenderUtil.label(context, mc.font, tag.screen().x, tag.screen().y, factor, parts, colors,
306
            ColorUtil.fade(background.getColor(), backgroundOpacity.getFloat() / 100f));
307
    }
308
309
    private static void addHealth(List<String> parts, List<Integer> colors, LivingEntity living) {
310
        float hp = EntityUtil.totalHealth(living);
311
        float max = EntityUtil.totalMaxHealth(living);
312
        parts.add(String.format(" %.0f", hp));
313
        colors.add(ColorUtil.health(max <= 0 ? 0 : hp / max));
314
    }
315
316
    private String nameText(Player player) {
317
        if (player != mc.player && displayName.isOn()) {
318
            return player.getDisplayName().getString();
319
        }
320
        return EntityUtil.displayNameOf(player);
321
    }
322
323
    private int playerNameColor(Player player) {
324
        if (EntityUtil.isFriend(player)) {
325
            return EntityUtil.FRIEND_COLOR;
326
        }
327
        return player == mc.player ? 0xFFB0FFB0 : nameColor.getColor();
328
    }
329
330
    private String gameModeText(Player player) {
331
        PlayerInfo info = tabEntry(player);
332
        if (info == null) {
333
            return "BOT";
334
        }
335
        GameType mode = info.getGameMode();
336
        return switch (mode) {
337
            case SURVIVAL -> "S";
338
            case CREATIVE -> "C";
339
            case ADVENTURE -> "A";
340
            case SPECTATOR -> "Sp";
341
        };
342
    }
343
344
    private static String typeName(Entity entity) {
345
        return entity.getType().getDescription().getString();
346
    }
347
348
    // Seconds with a tenth whilst short and whole minutes or hours beyond.
349
    private static String fuseText(int ticks) {
350
        if (ticks > TICKS_PER_HOUR) {
351
            return ticks / TICKS_PER_HOUR + " h";
352
        }
353
        if (ticks > TICKS_PER_MINUTE) {
354
            return ticks / TICKS_PER_MINUTE + " m";
355
        }
356
        return ticks / TICKS_PER_SECOND + "." + (ticks % TICKS_PER_SECOND) / 2 + " s";
357
    }
358
359
    private void drawGear(GuiGraphicsExtractor context, Tag tag, Player player, float factor) {
360
        if (!items.isOn() && !armor.isOn()) {
361
            return;
362
        }
363
        Font font = mc.font;
364
        ItemStack[] gear = new ItemStack[SLOTS.length];
365
        int[] widths = new int[SLOTS.length];
366
        List<List<Enchant>> enchants = new ArrayList<>();
367
        int total = 0;
368
        int deepest = 0;
369
        boolean any = false;
370
        for (int i = 0; i < SLOTS.length; i++) {
371
            gear[i] = slotItem(player, SLOTS[i]);
372
            any |= !gear[i].isEmpty();
373
            List<Enchant> list = enchantments.isOn() ? enchantsOf(gear[i]) : List.of();
374
            enchants.add(list);
375
            deepest = Math.max(deepest, list.size());
376
            if (!gear[i].isEmpty() || !ignoreEmpty.isOn()) {
377
                widths[i] = ITEM_SIZE + itemSpacing.getInt();
378
            }
379
            for (Enchant enchant : list) {
380
                widths[i] = Math.max(widths[i], enchantWidth(font, enchant));
381
            }
382
            total += widths[i];
383
        }
384
        if (!any) {
385
            return;
386
        }
387
388
        Matrix3x2fStack pose = context.pose();
389
        pose.pushMatrix();
390
        pose.translate((float) tag.screen().x, (float) tag.screen().y);
391
        pose.scale(factor, factor);
392
        context.guiRenderState.up();
393
        // The label background reaches two pixels above the point.
394
        int y = -ITEM_SIZE - 6;
395
        int x = -total / 2;
396
        for (int i = 0; i < SLOTS.length; i++) {
397
            ItemStack stack = gear[i];
398
            if (widths[i] == 0) {
399
                continue;
400
            }
401
            int iconX = x + (widths[i] - ITEM_SIZE - itemSpacing.getInt()) / 2;
402
            if (!stack.isEmpty()) {
403
                context.item(stack, iconX, y);
404
                drawDurability(context, font, stack, iconX, y);
405
            }
406
            drawEnchants(context, font, enchants.get(i), x, y, widths[i], deepest);
407
            x += widths[i];
408
        }
409
        pose.popMatrix();
410
    }
411
412
    private ItemStack slotItem(Player player, EquipmentSlot slot) {
413
        boolean hand = slot == EquipmentSlot.MAINHAND || slot == EquipmentSlot.OFFHAND;
414
        if (hand ? !items.isOn() : !armor.isOn()) {
415
            return ItemStack.EMPTY;
416
        }
417
        return player.getItemBySlot(slot);
418
    }
419
420
    private void drawDurability(GuiGraphicsExtractor context, Font font, ItemStack stack, int x, int y) {
421
        Durability mode = durability.getValue();
422
        if (mode == Durability.NONE || !stack.isDamageableItem()) {
423
            return;
424
        }
425
        if (mode == Durability.BAR) {
426
            context.itemDecorations(font, stack, x, y);
427
            return;
428
        }
429
        int left = stack.getMaxDamage() - stack.getDamageValue();
430
        String text = mode == Durability.NUMBER
431
            ? String.valueOf(left) : Math.round(left * 100f / stack.getMaxDamage()) + "%";
432
        context.guiRenderState.up();
433
        smallText(context, font, text, x, y, 0.75f, ColorUtil.withAlpha(stack.getBarColor(), 255));
434
    }
435
436
    private void drawEnchants(GuiGraphicsExtractor context, Font font, List<Enchant> list,
437
                              int x, int y, int width, int deepest) {
438
        if (list.isEmpty()) {
439
            return;
440
        }
441
        float size = 0.5f * enchantScale.getFloat();
442
        float lineHeight = font.lineHeight * size;
443
        float top = enchantPosition.is(EnchantPosition.ABOVE)
444
            ? y - (list.size() + 1) * lineHeight
445
            : y + (ITEM_SIZE - list.size() * lineHeight) / 2;
446
        context.guiRenderState.up();
447
        for (Enchant enchant : list) {
448
            float textX = x + (width - font.width(enchant.text()) * size) / 2;
449
            smallText(context, font, enchant.text(), textX, top, size, enchant.color());
450
            top += lineHeight;
451
        }
452
    }
453
454
    private static void smallText(GuiGraphicsExtractor context, Font font, String text,
455
                                  float x, float y, float size, int color) {
456
        Matrix3x2fStack pose = context.pose();
457
        pose.pushMatrix();
458
        pose.translate(x, y);
459
        pose.scale(size, size);
460
        context.text(font, text, 0, 0, color, true);
461
        pose.popMatrix();
462
    }
463
464
    private int enchantWidth(Font font, Enchant enchant) {
465
        return Math.round(font.width(enchant.text()) * 0.5f * enchantScale.getFloat());
466
    }
467
468
    // The chosen enchantments of a stack with curses in red.
469
    private List<Enchant> enchantsOf(ItemStack stack) {
470
        if (stack.isEmpty()) {
471
            return List.of();
472
        }
473
        ItemEnchantments all = EnchantmentHelper.getEnchantmentsForCrafting(stack);
474
        List<Enchant> list = new ArrayList<>();
475
        for (Holder<Enchantment> holder : all.keySet()) {
476
            String id = holder.unwrapKey().map(key -> key.identifier().toString()).orElse("");
477
            if (!shownEnchantments.contains(id)) {
478
                continue;
479
            }
480
            String name = holder.value().description().getString();
481
            String shortName = name.substring(0, Math.min(name.length(), enchantLetters.getInt()));
482
            int color = holder.is(EnchantmentTags.CURSE) ? RED : 0xFFFFFFFF;
483
            list.add(new Enchant(shortName + " " + all.getLevel(holder), color));
484
        }
485
        return list;
486
    }
487
488
    private PlayerInfo tabEntry(Player player) {
489
        return mc.getConnection() == null ? null : mc.getConnection().getPlayerInfo(player.getUUID());
490
    }
491
492
    // Ping from the tab list or -1 if the player is not on it.
493
    private int latencyOf(Player player) {
494
        PlayerInfo info = tabEntry(player);
495
        return info == null ? -1 : info.getLatency();
496
    }
497
}
498
CombatantVISUALSsrc/main/java/combatant/client/features/module/modules/visuals/NameTags.javaJava · 2,505 lines · 117.2 KB
SettingsnameTagsTogglesnameTagsDurabilityStartPercentnameTagsLimitDistancenameTagsDistanceTogglesnameTagsPlateDistancenameTagsSlotsDistancenameTagsEffectsDistancenameTagsNameplateAlphanameTagsPresentationModenameTagsWorldSizenameTagsDynamicWorldScalenameTagsDynamicWorldScaleCoefficientnameTagsPlayerHeadnameTagsNameplateExtrasnameTagsEnchantArmornameTagsEnchantMeleenameTagsEnchantToolsnameTagsEnchantBownameTagsEnchantFishingnameTagsEnchantTridentnameTagsEnchantCrossbownameTagsEnchantMacenameTagsEnchantOthernameTagsIllegalEnchantsAlwaysnameTagsOpponentAppleCooldownsnameTagsPvpPrefixnameTagsPvpPrefixColornameTagsHpDecimalsnameTagsHpColorMode
NameTags.javaJava · Minecraft 26.2 · 2,505 lines · 117.2 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
import combatant.client.render.engine.text.BuiltinFontCatalog;
11
import combatant.client.config.values.*;
12
import combatant.client.features.gui.hud.HudRenderSpace;
13
import combatant.client.features.module.*;
14
import combatant.client.features.module.Module;
15
import combatant.client.render.helpers.*;
16
import combatant.client.util.item.EnchantUtil;
17
import combatant.client.util.player.PlayerSkinResolver;
18
import it.unimi.dsi.fastutil.objects.Object2IntMap;
19
import net.minecraft.ChatFormatting;
20
import net.minecraft.client.CameraType;
21
import net.minecraft.client.Minecraft;
22
import net.minecraft.client.gui.GuiGraphicsExtractor;
23
import net.minecraft.client.gui.Hud;
24
import net.minecraft.client.multiplayer.PlayerInfo;
25
import net.minecraft.client.player.AbstractClientPlayer;
26
import net.minecraft.client.resources.language.I18n;
27
import net.minecraft.client.renderer.texture.TextureAtlas;
28
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
29
import net.minecraft.core.Holder;
30
import net.minecraft.data.AtlasIds;
31
import net.minecraft.network.chat.Component;
32
import net.minecraft.network.chat.MutableComponent;
33
import net.minecraft.resources.Identifier;
34
import net.minecraft.resources.ResourceKey;
35
import net.minecraft.util.Mth;
36
import net.minecraft.world.effect.MobEffectInstance;
37
import net.minecraft.world.entity.Entity;
38
import net.minecraft.world.entity.EquipmentSlot;
39
import net.minecraft.world.entity.player.Player;
40
import net.minecraft.world.item.Item;
41
import net.minecraft.world.item.ItemStack;
42
import net.minecraft.world.item.Items;
43
import net.minecraft.world.item.enchantment.Enchantment;
44
import net.minecraft.world.item.enchantment.EnchantmentHelper;
45
import net.minecraft.world.item.enchantment.ItemEnchantments;
46
import net.minecraft.world.level.GameType;
47
import net.minecraft.world.phys.AABB;
48
import net.minecraft.world.phys.Vec3;
49
import combatant.client.config.SettingDef;
50
import combatant.client.config.common.CommonSettingSchemas;
51
import combatant.client.features.gui.clickgui.settings.TextListSetting;
52
import combatant.client.features.module.modules.combat.PvpCooldowns;
53
import combatant.client.features.relations.CategoryService;
54
import combatant.client.features.relations.PlayerRelations;
55
import combatant.client.mixininterface.IEntity;
56
import combatant.client.render.engine.animation.AnimationUtility;
57
import combatant.client.render.engine.color.RenderColor;
58
import combatant.client.render.engine.RenderState;
59
import combatant.client.render.engine.core.ViewportContext;
60
import combatant.client.render.engine.renderer.Renderer2D;
61
import combatant.client.render.engine.renderer.Renderer3D;
62
import combatant.client.render.engine.renderer.ui.ItemBatchRenderer;
63
import combatant.client.render.engine.text.RuntimeTextLayout;
64
import combatant.client.render.engine.text.TextRenderer;
65
import combatant.client.render.engine.text.WorldTextRenderer;
66
import combatant.client.render.engine.world.WorldBillboardRenderer;
67
import combatant.client.render.engine.world.WorldUiPresentationService;
68
import combatant.client.util.item.EnchantMeta;
69
import combatant.client.util.item.EnchantRegistry;
70
import combatant.client.util.item.IllegalItemUtil;
71
import combatant.client.util.item.RarityColorUtil;
72
import combatant.client.util.item.TopEnchantUtil;
73
import combatant.client.util.player.PlayerHealthResolver;
74
import combatant.client.util.player.effect.StatusEffectTracker;
75
import combatant.client.util.player.effect.StatusEffectView;
76
import combatant.client.util.pvp.CooldownRegistry;
77
import combatant.client.util.pvp.ItemCooldownSnapshot;
78
import combatant.client.util.pvp.PvpTargetState;
79
import combatant.client.util.pvp.opponents.OpponentCooldownManager;
80
import combatant.client.util.pvp.opponents.TotemPopCounter;
81
import combatant.client.util.pvp.opponents.TotemPopSnapshot;
82
import combatant.client.util.text.LegacyTextUtil;
83
import combatant.client.util.text.TextRenderUtil;
84
85
import java.util.*;
86
87
88
//todo Description
89
@ModuleInfo(id = "nametags", displayName = "NameTags", aliases = {"nametag", "tags", "names"}, category = ModuleCategory.VISUALS)
90
public class NameTags extends Module {
91
92
    // Screen-space geometry is authored directly in UNSCALED_LOGICAL units.
93
    // No GUI-scale/framebuffer multipliers belong in the feature code.
94
    // rich_src is used only as a visual reference. Its 2x presentation has already
95
    // been baked into these direct logical-unit constants; there is no runtime GUI-scale math.
96
    private static final float RICH_TEXT_LOGICAL_HEIGHT = 20.0f;
97
    private static final float NAMEPLATE_SCALE = 1.06f;
98
    private static final float SMALL_TEXT_SCALE = 0.88f;
99
100
    private static final int ICON_SIZE = 24;
101
    private static final int ICON_GAP = 5;
102
    private static final int EQUIP_ICON_SIZE = 28;
103
    private static final int EQUIP_ICON_GAP = 6;
104
    private static final int EFFECT_LINE_HEIGHT = 26;
105
    private static final int EFFECT_X_OFFSET = 6;
106
    private static final int EFFECT_LEVEL_COLOR = 0xFFBFC6D1;
107
    private static final int EFFECT_ROW_GAP = 10;
108
    private static final int EFFECT_ROW_ICON_GAP = 8;
109
    private static final int EFFECT_ROW_TEXT_GAP = 4;
110
    private static final int EFFECT_ROW_LEVEL_GAP = 3;
111
    private static final int EFFECT_ROW_TIME_GAP = 2;
112
    private static final float EFFECT_ROW_SCALE = 1.15f;
113
114
    private static final float NAMEPLATE_PAD_X = 4.4f;
115
    private static final float NAMEPLATE_PAD_Y = 1.65f;
116
    private static final float MATTE_NAMEPLATE_RADIUS = 4.4f;
117
    private static final float MATTE_HEAD_MIN_SIZE = 18.0f;
118
    private static final float MATTE_HEAD_DIVIDER_GAP = 4.4f;
119
    private static final float MATTE_HEAD_DIVIDER_WIDTH = 1.1f;
120
    private static final float MATTE_HEAD_TEXT_GAP = 4.4f;
121
    private static final float TOTEM_BADGE_GAP = 4.4f;
122
    private static final float TOTEM_BADGE_DIVIDER_WIDTH = 1.1f;
123
    private static final float TOTEM_BADGE_DIVIDER_GAP = 4.4f;
124
    private static final float TOTEM_BADGE_MIN_WIDTH = 24.0f;
125
    private static final float TOTEM_BADGE_PAD_X = 4.0f;
126
    private static final float TOTEM_BADGE_ICON_SIZE = 18.0f;
127
    private static final float TOTEM_BADGE_TEXT_GAP = 3.3f;
128
    private static final float TOTEM_BADGE_TEXT_SCALE = NAMEPLATE_SCALE;
129
    private static final float TOTEM_BADGE_ANIM_SPEED = 10.0f;
130
    private static final float ENCHANT_TEXT_MIN_GAP = 2.0f;
131
    private static final int ENCHANT_NAME_MAX_CODEPOINTS = 2;
132
    private static final WorldUiPresentationService.Policy WORLD_PRESENTATION_POLICY =
133
            WorldUiPresentationService.Policy.defaults();
134
    private static final int DIST_TEXT_GAP = 5;
135
    private static final int PING_TEXT_GAP = 5;
136
    private static final int HP_TEXT_GAP = 5;
137
    private static final int HP_GREEN = 0xFF55FF55;
138
    private static final int HP_CYAN = 0xFF55FFFF;
139
    private static final int HP_RED = 0xFFFF5555;
140
    private static final int INFO_COLOR_DEFAULT = 0xFFFF8A8A;
141
    private static final int EFFECT_LEVEL_STACK_COLOR = 0xFFFF4444;
142
    private static final int EFFECT_TIME_COLOR = 0xFFCCCCCC;
143
    private static final int OPP_TIME_COLOR = 0xFFFFFFFF;
144
    private static final int OPP_TIME_COLOR_GRACE = 0xFF4DA6FF;
145
    private static final int OPP_STACK_Y_OFFSET = 10;
146
    private static final int OPPONENT_DISTANCE = 80;
147
    private static final int EFFECT_CACHE_TICKS = 4;
148
    private static final int ENCHANT_CACHE_TICKS = 2;
149
    private static final ItemStack[] EMPTY_SLOTS = new ItemStack[0];
150
    private static ItemStack totemBadgeStack;
151
152
    private static ItemStack totemBadgeStack() {
153
        if (totemBadgeStack == null || totemBadgeStack.isEmpty()) {
154
            totemBadgeStack = new ItemStack(Items.TOTEM_OF_UNDYING);
155
        }
156
        return totemBadgeStack;
157
    }
158
    private static final String SETTING_TOGGLES = "toggles";
159
    private static final String SETTING_DURABILITY_START = "durability_start_percent";
160
    private static final String SETTING_LIMIT_DISTANCE = "limit_distance";
161
    private static final String SETTING_DISTANCE_TOGGLES = "distance_toggles";
162
    private static final String SETTING_NAMEPLATE_CUTOFF = "nameplate_cutoff";
163
    private static final String SETTING_SLOTS_CUTOFF = "slots_cutoff";
164
    private static final String SETTING_EFFECTS_CUTOFF = "effects_cutoff";
165
    private static final String SETTING_ARMOR_ENCHANTS = "armor_enchants";
166
    private static final String SETTING_MELEE_ENCHANTS = "melee_enchants";
167
    private static final String SETTING_TOOLS_ENCHANTS = "tools_enchants";
168
    private static final String SETTING_BOW_ENCHANTS = "bow_enchants";
169
    private static final String SETTING_FISHING_ENCHANTS = "fishing_enchants";
170
    private static final String SETTING_TRIDENT_ENCHANTS = "trident_enchants";
171
    private static final String SETTING_CROSSBOW_ENCHANTS = "crossbow_enchants";
172
    private static final String SETTING_MACE_ENCHANTS = "mace_enchants";
173
    private static final String SETTING_OTHER_ENCHANTS = "other_enchants";
174
    private static final String SETTING_ILLEGAL_ENCHANT_COLOR = "illegal_enchant_color";
175
    private static final String SETTING_ILLEGAL_ENCHANTS_ALWAYS = "illegal_enchants_always";
176
    private static final String SETTING_TOP_ENCHANT_COLOR = "top_enchant_color";
177
    private static final String SETTING_TOP_ENCHANT_IGNORE_LIST = "top_enchant_ignore_list";
178
    private static final String SETTING_DEFAULT_NAME_COLOR = "default_name_color";
179
    private static final String SETTING_FRIEND_NAME_COLOR = "friend_name_color";
180
    private static final String SETTING_ENEMY_NAME_COLOR = "enemy_name_color";
181
    private static final String SETTING_STAFF_NAME_COLOR = "staff_name_color";
182
    private static final String SETTING_HP_DECIMALS = "hp_decimals";
183
    private static final String SETTING_HP_COLOR_MODE = "hp_color_mode";
184
    private static final String SETTING_NAMEPLATE_ALPHA = "nameplate_alpha";
185
    private static final String SETTING_PRESENTATION_MODE = "presentation_mode";
186
    private static final String SETTING_WORLD_SIZE = "world_size";
187
    private static final String SETTING_DYNAMIC_WORLD_SCALE = "dynamic_world_scale";
188
    private static final String SETTING_DYNAMIC_WORLD_SCALE_COEFFICIENT = "dynamic_world_scale_coefficient";
189
    private static final String SETTING_PLAYER_HEAD = "player_head";
190
    private static final String SETTING_NAMEPLATE_EXTRAS = "nameplate_extras";
191
    // Match ESP.java projected player box exactly, then place both external blocks
192
    // from that same visual reference so top/bottom spacing stays symmetric.
193
    private static final double ESP_REFERENCE_TOP_OFFSET = 0.18;
194
    private static final float FRAME_CONTENT_GAP = 3.5f;
195
    private static final float EQUIPMENT_TO_NAMEPLATE_GAP = 5.0f;
196
    private static final int REFERENCE_BACKDROP_ALPHA = 148;
197
    private static final int REFERENCE_BACKDROP_RGB = 0x000000;
198
    private static final int REFERENCE_DIVIDER_RGB = 0xFFFFFF;
199
    private static final int REFERENCE_DIVIDER_ALPHA = 72;
200
    private static final float MAIN_HAND_PAD_X = 4.4f;
201
    private static final float MAIN_HAND_PAD_Y = 1.65f;
202
    private static final float MAIN_HAND_ICON_SIZE = 18.0f;
203
    private static final float MAIN_HAND_ICON_GAP = 4.4f;
204
    private static final float MAIN_HAND_TEXT_SCALE = NAMEPLATE_SCALE;
205
    private static final float MAIN_HAND_RADIUS = 4.4f;
206
    private static final String SETTING_OPPONENT_APPLE_COOLDOWNS = "opponent_apple_cooldowns";
207
    private static final String SETTING_PVP_PREFIX = "pvp_prefix";
208
    private static final String SETTING_PVP_PREFIX_COLOR = "pvp_prefix_color";
209
    private final Minecraft mc = Minecraft.getInstance();
210
    private final ItemIdSetValue topIgnore = TopEnchantUtil.ignoreValue();
211
    private final List<RenderEntry> renderQueue = new ArrayList<>();
212
    private final List<WorldRenderEntry> worldRenderQueue = new ArrayList<>();
213
    private final List<ItemBatchRenderer.WorldItemRow> worldItemRows = new ArrayList<>();
214
    private final List<Player> playerBuffer = new ArrayList<>();
215
    private final Map<UUID, ItemStack[]> slotCache = new HashMap<>();
216
    private final Map<UUID, EffectCache> effectCache = new HashMap<>();
217
    private final Map<UUID, EnchantCache> enchantCache = new HashMap<>();
218
    private final Map<UUID, Float> totemPopAnimations = new HashMap<>();
219
    private final Map<UUID, Integer> totemPopLastCounts = new HashMap<>();
220
    private final HashSet<UUID> seenIds = new HashSet<>();
221
    private final BooleanMapValue toggles = group("nameTagsToggles", SETTING_TOGGLES, Map.of(
222
            "Show nameplate", true,
223
            "Show distance", true,
224
            "Show armor row", true,
225
            "Show main hand", true,
226
            "Item durability bar", true,
227
            "Show effects", true,
228
            "Show self in 3rd person", false
229
    ));
230
    private final NumberValue<Integer> durabilityStartPercent =
231
            visibleWhen(num("nameTagsDurabilityStartPercent", SETTING_DURABILITY_START, 99, 0, 100),
232
                    () -> toggles.get("Item durability bar"));
233
    private final BooleanValue limitDistance =
234
            visibleWhen(bool("nameTagsLimitDistance", SETTING_LIMIT_DISTANCE, false),
235
                    () -> toggles.get("Show nameplate") || toggles.get("Show main hand")
236
                            || toggles.get("Show armor row") || toggles.get("Show effects"));
237
    private final BooleanMapValue distanceToggles =
238
            visibleWhen(group("nameTagsDistanceToggles", SETTING_DISTANCE_TOGGLES, Map.of(
239
                    "nameplate", true,
240
                    "slots", true,
241
                    "effects", true
242
            )), () -> limitDistance.get() && (toggles.get("Show nameplate") || toggles.get("Show main hand")
243
                    || toggles.get("Show armor row") || toggles.get("Show effects")));
244
    private final NumberValue<Integer> plateDistance =
245
            visibleWhen(num("nameTagsPlateDistance", SETTING_NAMEPLATE_CUTOFF, 80, 5, 256),
246
                    () -> usesDistanceCutoff("nameplate") && (toggles.get("Show nameplate") || toggles.get("Show main hand")));
247
    private final NumberValue<Integer> slotsDistance =
248
            visibleWhen(num("nameTagsSlotsDistance", SETTING_SLOTS_CUTOFF, 70, 5, 256),
249
                    () -> usesDistanceCutoff("slots") && toggles.get("Show armor row"));
250
    private final NumberValue<Integer> effectsDistance =
251
            visibleWhen(num("nameTagsEffectsDistance", SETTING_EFFECTS_CUTOFF, 90, 5, 256),
252
                    () -> usesDistanceCutoff("effects") && toggles.get("Show effects"));
253
    private final NumberValue<Integer> nameplateAlpha =
254
            visibleWhen(num("nameTagsNameplateAlpha", SETTING_NAMEPLATE_ALPHA, REFERENCE_BACKDROP_ALPHA, 0, 255),
255
                    () -> toggles.get("Show nameplate"));
256
    private final EnumValue<PresentationMode> presentationMode =
257
            enumSetting("nameTagsPresentationMode", SETTING_PRESENTATION_MODE, PresentationMode.HYBRID, PresentationMode.values());
258
    private final NumberValue<Float> worldSize =
259
            visibleWhen(num("nameTagsWorldSize", SETTING_WORLD_SIZE, 0.72f, 0.35f, 1.50f),
260
                    () -> presentationMode.get() != PresentationMode.TWO_D);
261
    private final BooleanValue dynamicWorldScale =
262
            visibleWhen(bool("nameTagsDynamicWorldScale", SETTING_DYNAMIC_WORLD_SCALE, true),
263
                    () -> presentationMode.get() != PresentationMode.TWO_D);
264
    private final NumberValue<Float> dynamicWorldScaleCoefficient =
265
            visibleWhen(num("nameTagsDynamicWorldScaleCoefficient", SETTING_DYNAMIC_WORLD_SCALE_COEFFICIENT, 0.25f, 0.0f, 1.0f),
266
                    () -> presentationMode.get() != PresentationMode.TWO_D && dynamicWorldScale.get());
267
    private final BooleanValue playerHead =
268
            visibleWhen(bool("nameTagsPlayerHead", SETTING_PLAYER_HEAD, false),
269
                    () -> toggles.get("Show nameplate"));
270
    private final BooleanMapValue nameplateExtras = visibleWhen(group("nameTagsNameplateExtras", SETTING_NAMEPLATE_EXTRAS, new LinkedHashMap<>() {{
271
        put("Tab names", false);
272
        put("Ping", false);
273
    }}), () -> toggles.get("Show nameplate"));
274
    private final BooleanMapValue enchantArmor = group("nameTagsEnchantArmor", SETTING_ARMOR_ENCHANTS, Map.ofEntries(
275
            Map.entry("protection", true),
276
            Map.entry("fire_protection", false),
277
            Map.entry("feather_falling", false),
278
            Map.entry("blast_protection", false),
279
            Map.entry("projectile_protection", false),
280
            Map.entry("respiration", false),
281
            Map.entry("aqua_affinity", false),
282
            Map.entry("thorns", true),
283
            Map.entry("depth_strider", false),
284
            Map.entry("frost_walker", false),
285
            Map.entry("soul_speed", false),
286
            Map.entry("swift_sneak", false)
287
    ));
288
    private final BooleanMapValue enchantMelee = group("nameTagsEnchantMelee", SETTING_MELEE_ENCHANTS, Map.ofEntries(
289
            Map.entry("sharpness", true),
290
            Map.entry("smite", false),
291
            Map.entry("bane_of_arthropods", false),
292
            Map.entry("knockback", true),
293
            Map.entry("fire_aspect", true),
294
            Map.entry("looting", true),
295
            Map.entry("sweeping_edge", false)
296
    ));
297
    private final BooleanMapValue enchantTools = group("nameTagsEnchantTools", SETTING_TOOLS_ENCHANTS, Map.ofEntries(
298
            Map.entry("efficiency", true),
299
            Map.entry("silk_touch", true),
300
            Map.entry("fortune", true)
301
    ));
302
    private final BooleanMapValue enchantBow = group("nameTagsEnchantBow", SETTING_BOW_ENCHANTS, Map.ofEntries(
303
            Map.entry("power", true),
304
            Map.entry("punch", true),
305
            Map.entry("flame", false),
306
            Map.entry("infinity", false)
307
    ));
308
    private final BooleanMapValue enchantFishing = group("nameTagsEnchantFishing", SETTING_FISHING_ENCHANTS, Map.ofEntries(
309
            Map.entry("luck_of_the_sea", false),
310
            Map.entry("lure", false)
311
    ));
312
    private final BooleanMapValue enchantTrident = group("nameTagsEnchantTrident", SETTING_TRIDENT_ENCHANTS, Map.ofEntries(
313
            Map.entry("loyalty", false),
314
            Map.entry("impaling", false),
315
            Map.entry("riptide", false),
316
            Map.entry("channeling", false)
317
    ));
318
    private final BooleanMapValue enchantCrossbow = group("nameTagsEnchantCrossbow", SETTING_CROSSBOW_ENCHANTS, Map.ofEntries(
319
            Map.entry("multishot", false),
320
            Map.entry("quick_charge", false),
321
            Map.entry("piercing", true)
322
    ));
323
    private final BooleanMapValue enchantMace = group("nameTagsEnchantMace", SETTING_MACE_ENCHANTS, Map.ofEntries(
324
            Map.entry("density", true),
325
            Map.entry("breach", false),
326
            Map.entry("wind_burst", true)
327
    ));
328
    private final BooleanMapValue enchantOther = group("nameTagsEnchantOther", SETTING_OTHER_ENCHANTS, Map.ofEntries(
329
            Map.entry("mending", false),
330
            Map.entry("unbreaking", false),
331
            Map.entry("vanishing_curse", false),
332
            Map.entry("lunge", true)
333
    ));
334
    private final BooleanValue illegalEnchantsAlways = bool("nameTagsIllegalEnchantsAlways", SETTING_ILLEGAL_ENCHANTS_ALWAYS, true);
335
    private final BooleanValue opponentAppleCooldowns = bool("nameTagsOpponentAppleCooldowns", SETTING_OPPONENT_APPLE_COOLDOWNS, true);
336
    private final BooleanValue totemPopCounter = TotemPopCounter.enabledValue();
337
    private final NumberValue<Integer> totemPopResetSeconds = TotemPopCounter.resetAfterSecondsValue();
338
    private final BooleanValue pvpPrefix = bool("nameTagsPvpPrefix", SETTING_PVP_PREFIX, false);
339
    private final RGBColorValue pvpPrefixColor =
340
            visibleWhen(colorNoAlpha("nameTagsPvpPrefixColor", SETTING_PVP_PREFIX_COLOR, "#FF0000"), pvpPrefix::get);
341
    private final BooleanValue hpDecimals =
342
            visibleWhen(bool("nameTagsHpDecimals", SETTING_HP_DECIMALS, false),
343
                    () -> toggles.get("Show nameplate"));
344
    private final ModeValue hpColorMode =
345
            visibleWhen(modeSetting("nameTagsHpColorMode", SETTING_HP_COLOR_MODE, "Static", "Static", "Gradient"),
346
                    () -> toggles.get("Show nameplate"));
347
    private transient TextRenderer cachedNameTr;
348
    private transient TextRenderer cachedHpTr;
349
    private transient TextRenderer cachedLevelTr;
350
    private transient TextRenderer cachedTimeTr;
351
    private transient float foregroundAlpha = 1.0f;
352
353
    {
354
        setting(SettingDef.bool(totemPopCounter)
355
                .common(CommonSettingSchemas.TOTEM_POP_COUNTER.commonI18nKey()));
356
        setting(SettingDef.number(totemPopResetSeconds)
357
                .common(CommonSettingSchemas.TOTEM_POP_RESET_SECONDS.commonI18nKey())
358
                .visibleWhen(totemPopCounter::get));
359
        setting(SettingDef.colorNoAlpha(SETTING_ILLEGAL_ENCHANT_COLOR, IllegalItemUtil.illegalColorValue()));
360
        setting(SettingDef.colorNoAlpha(SETTING_TOP_ENCHANT_COLOR, TopEnchantUtil.topColorValue()));
361
        setting(SettingDef.textList(SETTING_TOP_ENCHANT_IGNORE_LIST, topIgnore, TextListSetting.PickerMode.ENCHANTMENTS));
362
    }
363
364
    private static int withAlpha(int argb, int alpha) {
365
        return (argb & 0x00FFFFFF) | (alpha << 24);
366
    }
367
368
    private static String formatNameplateHp(String hp) {
369
        return hp == null || hp.isEmpty() ? "" : "[" + hp + "]";
370
    }
371
372
    private static int clampAlpha(int a) {
373
        if (a < 0) return 0;
374
        if (a > 255) return 255;
375
        return a;
376
    }
377
378
    private static int equipmentSignature(ItemStack[] slots) {
379
        if (slots == null || slots.length == 0) return 1;
380
        int hash = 1;
381
        for (ItemStack stack : slots) {
382
            hash = 31 * hash + itemSignature(stack);
383
        }
384
        return hash;
385
    }
386
387
    private static int itemSignature(ItemStack stack) {
388
        if (stack == null || stack.isEmpty()) return 0;
389
        int hash = 17;
390
        hash = 31 * hash + Item.getId(stack.getItem());
391
        hash = 31 * hash + stack.getCount();
392
        hash = 31 * hash + stack.getDamageValue();
393
        hash = 31 * hash + stack.getComponents().hashCode();
394
        return hash;
395
    }
396
397
    private static int scaleRow(int value) {
398
        return Math.round(value * EFFECT_ROW_SCALE);
399
    }
400
401
    private static int equipIconSize() {
402
        return EQUIP_ICON_SIZE;
403
    }
404
405
    private static int equipIconGap() {
406
        return EQUIP_ICON_GAP;
407
    }
408
409
    private static int resolvePingColor(int ping) {
410
        if (ping < 0) {
411
            return 0xFFD0D0D0;
412
        }
413
        if (ping <= 70) {
414
            return 0xFF55FF55;
415
        }
416
        if (ping >= 200) {
417
            return 0xFFFF5555;
418
        }
419
420
        if (ping <= 135) {
421
            float t = (ping - 70.0f) / 65.0f;
422
            return mixColor(0xFF55FF55, 0xFFFFFF55, t);
423
        }
424
425
        float t = (ping - 135.0f) / 65.0f;
426
        return mixColor(0xFFFFFF55, 0xFFFF5555, t);
427
    }
428
429
    private static int mixColor(int start, int end, float t) {
430
        t = Mth.clamp(t, 0.0f, 1.0f);
431
        int sa = (start >>> 24) & 0xFF;
432
        int sr = (start >>> 16) & 0xFF;
433
        int sg = (start >>> 8) & 0xFF;
434
        int sb = start & 0xFF;
435
        int ea = (end >>> 24) & 0xFF;
436
        int er = (end >>> 16) & 0xFF;
437
        int eg = (end >>> 8) & 0xFF;
438
        int eb = end & 0xFF;
439
        int a = (int) (sa + (ea - sa) * t + 0.5f);
440
        int r = (int) (sr + (er - sr) * t + 0.5f);
441
        int g = (int) (sg + (eg - sg) * t + 0.5f);
442
        int b = (int) (sb + (eb - sb) * t + 0.5f);
443
        return (a << 24) | (r << 16) | (g << 8) | b;
444
    }
445
446
    private static boolean beginTextRenderer(TextRenderer textRenderer, double scale) {
447
        if (textRenderer == null || textRenderer.isBuilding()) return false;
448
        textRenderer.begin(scale);
449
        return true;
450
    }
451
452
    private static void endTextRenderer(TextRenderer textRenderer, boolean started) {
453
        if (!started || textRenderer == null || !textRenderer.isBuilding()) return;
454
        textRenderer.end();
455
    }
456
457
    private static int lerpColor(int a, int b, float t) {
458
        int aA = (a >>> 24) & 0xFF;
459
        int aR = (a >>> 16) & 0xFF;
460
        int aG = (a >>> 8) & 0xFF;
461
        int aB = a & 0xFF;
462
        int bA = (b >>> 24) & 0xFF;
463
        int bR = (b >>> 16) & 0xFF;
464
        int bG = (b >>> 8) & 0xFF;
465
        int bB = b & 0xFF;
466
        int oA = Math.round(lerp(aA, bA, t));
467
        int oR = Math.round(lerp(aR, bR, t));
468
        int oG = Math.round(lerp(aG, bG, t));
469
        int oB = Math.round(lerp(aB, bB, t));
470
        return (oA << 24) | (oR << 16) | (oG << 8) | oB;
471
    }
472
473
    private static float lerp(float a, float b, float t) {
474
        return a + (b - a) * t;
475
    }
476
477
    private static boolean hasOpponentCooldowns(UUID playerId) {
478
        if (playerId == null) return false;
479
        for (Item item : CooldownRegistry.trackedItems()) {
480
            if (OpponentCooldownManager.snapshot(playerId, item).visible()) {
481
                return true;
482
            }
483
        }
484
        return false;
485
    }
486
487
    private static String secondsTextInt(float secondsLeft) {
488
        int sec = Math.max(0, (int) Math.ceil(secondsLeft));
489
        return String.valueOf(sec);
490
    }
491
492
    private static boolean pushNameplateScissor(NameplateLayout layout) {
493
        if (layout == null) return false;
494
        Minecraft mc = Minecraft.getInstance();
495
        if (mc == null || mc.getWindow() == null) return false;
496
497
        int sw = mc.getWindow().getScreenWidth();
498
        int sh = mc.getWindow().getScreenHeight();
499
500
        int x1 = Math.max(0, (int) Math.floor(layout.bgX()));
501
        int y1 = Math.max(0, (int) Math.floor(layout.bgY()));
502
        int x2 = Math.min(sw, (int) Math.ceil(layout.bgX() + layout.bgW()));
503
        int y2 = Math.min(sh, (int) Math.ceil(layout.bgY() + layout.bgH()));
504
505
        if (x2 <= x1 || y2 <= y1) return false;
506
        return ScissorFunction.pushRawRect(x1, y1, x2, y2);
507
    }
508
509
    private static int computeOpponentStackX(NameplateLayout layout, int centerX) {
510
        if (layout != null) {
511
            return (int) Math.ceil(layout.bgX() + layout.bgW()) + EFFECT_X_OFFSET;
512
        }
513
        return centerX + (ICON_SIZE + ICON_GAP) * 2 + EFFECT_X_OFFSET;
514
    }
515
516
    private static int computeOpponentStackY(int nameY) {
517
        return nameY + OPP_STACK_Y_OFFSET;
518
    }
519
520
    @Override
521
    public HudRenderSpace getHudRenderSpace() {
522
        return HudRenderSpace.UNSCALED_LOGICAL;
523
    }
524
525
    @Override
526
    public HudPhase getHudPhase() {
527
        return HudPhase.AFTER_MISC_OVERLAYS;
528
    }
529
530
    @Override
531
    public WorldPhase getWorldPhase() {
532
        return WorldPhase.END_MAIN_BILLBOARD;
533
    }
534
535
    @Override
536
    public void onRenderWorldEngine(Renderer3D renderer, Renderer3D depthRenderer, float tickDelta) {
537
        if (!isEnabled() || renderer == null || mc.level == null || mc.player == null) return;
538
        if (presentationMode.get() == PresentationMode.TWO_D) return;
539
540
        ensureFontCache(TextRenderer.get());
541
        StatusEffectView.sync(mc);
542
        TotemPopCounter.tick();
543
        float dt = AnimationUtility.deltaTime();
544
545
        worldRenderQueue.clear();
546
        worldItemRows.clear();
547
        seenIds.clear();
548
        Vec3 cameraPos = mc.gameRenderer != null && mc.gameRenderer.mainCamera() != null
549
                ? mc.gameRenderer.mainCamera().position()
550
                : mc.player.position();
551
        WorldBillboardRenderer.Basis basis = WorldBillboardRenderer.currentBasis();
552
553
        for (Player player : mc.level.players()) {
554
            if (!shouldRender(player)) continue;
555
            seenIds.add(player.getUUID());
556
557
            TotemPopSnapshot totemPopSnapshot = TotemPopCounter.snapshot(player.getUUID());
558
            float totemPopAnimation = updateTotemPopAnimation(player, totemPopSnapshot, dt);
559
            int totemPopCount = resolveTotemPopCount(player, totemPopSnapshot, totemPopAnimation);
560
561
            Vec3 pos = obtainEntityLerpedPos(player, tickDelta);
562
            double dist = cameraPos.distanceTo(pos);
563
            WorldUiPresentationService.Snapshot presentation = resolvePresentation(dist);
564
            float alpha = presentation.worldAlpha();
565
            if (alpha <= 0.001f) continue;
566
567
            boolean renderNameplate = toggles.get("Show nameplate")
568
                    && (!usesDistanceCutoff("nameplate") || dist <= plateDistance.get());
569
            boolean renderMainHand = toggles.get("Show main hand")
570
                    && (!usesDistanceCutoff("nameplate") || dist <= plateDistance.get())
571
                    && !player.getMainHandItem().isEmpty();
572
            boolean renderSlots = toggles.get("Show armor row")
573
                    && (!usesDistanceCutoff("slots") || dist <= slotsDistance.get());
574
            boolean renderEffects = toggles.get("Show effects")
575
                    && (!usesDistanceCutoff("effects") || dist <= effectsDistance.get());
576
            if (!renderNameplate && !renderMainHand && !renderSlots && !renderEffects) continue;
577
578
            double adaptiveScale = presentation.worldUnitsPerPixel();
579
            AABB projectedBox = player.getBoundingBox().move(pos.subtract(player.position())).inflate(0.1);
580
            Vec3 anchor = new Vec3(projectedBox.getCenter().x, projectedBox.maxY, projectedBox.getCenter().z);
581
            Vec3 bottomAnchor = new Vec3(projectedBox.getCenter().x, projectedBox.minY, projectedBox.getCenter().z);
582
583
            ItemStack[] slots = renderSlots ? getCachedEquipmentSlots(player) : EMPTY_SLOTS;
584
            List<List<EnchantLine>> enchantLines = List.of();
585
            int maxEnchantLines = 0;
586
            if (renderSlots) {
587
                EnchantCache cache = resolveEnchantCache(player, slots);
588
                enchantLines = cache.lines;
589
                maxEnchantLines = cache.maxLines;
590
            }
591
592
            List<MobEffectInstance> effects = renderEffects ? resolveEffects(player) : List.of();
593
            boolean renderTotemBadge = renderNameplate
594
                    && totemPopCounter.get()
595
                    && totemPopCount > 0
596
                    && totemPopAnimation > 0.001f;
597
            ItemStack mainHand = renderMainHand ? player.getMainHandItem().copy() : ItemStack.EMPTY;
598
            int extraWorldItems = (renderTotemBadge ? 1 : 0) + (renderMainHand ? 1 : 0);
599
            ItemStack[] worldItems = extraWorldItems == 0
600
                    ? slots
601
                    : Arrays.copyOf(slots, slots.length + extraWorldItems);
602
            int worldItemCursor = slots.length;
603
            if (renderTotemBadge) {
604
                worldItems[worldItemCursor++] = totemBadgeStack();
605
            }
606
            if (renderMainHand) {
607
                worldItems[worldItemCursor] = mainHand;
608
            }
609
610
            worldRenderQueue.add(new WorldRenderEntry(
611
                    player, anchor, bottomAnchor, dist, adaptiveScale, alpha,
612
                    renderNameplate, renderSlots, renderEffects,
613
                    slots, enchantLines, maxEnchantLines, effects,
614
                    totemPopCount, totemPopAnimation, mainHand, renderMainHand, worldItems
615
            ));
616
        }
617
618
        worldRenderQueue.sort(Comparator.comparingDouble(WorldRenderEntry::distance).reversed());
619
        for (int i = 0; i < worldRenderQueue.size(); i++) {
620
            WorldRenderEntry entry = worldRenderQueue.get(i);
621
            worldItemRows.add(new ItemBatchRenderer.WorldItemRow(entry.player(), entry.worldItems(), i * 31));
622
        }
623
624
        List<ItemBatchRenderer.WorldItemSprite[]> itemSprites =
625
                ItemBatchRenderer.resolveWorldItemSprites(worldItemRows);
626
        for (int i = 0; i < worldRenderQueue.size(); i++) {
627
            ItemBatchRenderer.WorldItemSprite[] rowSprites = i < itemSprites.size()
628
                    ? itemSprites.get(i)
629
                    : new ItemBatchRenderer.WorldItemSprite[0];
630
            renderWorldNameTag(renderer, basis, worldRenderQueue.get(i), rowSprites);
631
        }
632
633
        if (presentationMode.get() == PresentationMode.THREE_D) pruneCaches();
634
    }
635
636
    @Override
637
    public void onRender2D(GuiGraphicsExtractor ctx, float tickDelta) {
638
    }
639
640
    @Override
641
    public void onRenderHudEngine(Renderer2D renderer, TextRenderer textRenderer, GuiGraphicsExtractor ctx, float tickDelta) {
642
        if (!isEnabled() || mc.level == null || mc.player == null) return;
643
644
        if (presentationMode.get() == PresentationMode.THREE_D) {
645
            renderQueue.clear();
646
            return;
647
        }
648
649
        ensureFontCache(textRenderer);
650
651
        StatusEffectView.sync(mc);
652
        TotemPopCounter.tick();
653
        boolean advanceTotemAnimationHere = presentationMode.get() == PresentationMode.TWO_D;
654
        float dt = advanceTotemAnimationHere ? AnimationUtility.deltaTime() : 0.0f;
655
656
        renderQueue.clear();
657
        playerBuffer.clear();
658
        seenIds.clear();
659
660
        boolean wantNameplate = toggles.get("Show nameplate");
661
        boolean wantMainHand = toggles.get("Show main hand");
662
        boolean wantSlots = toggles.get("Show armor row");
663
        boolean wantEffects = toggles.get("Show effects");
664
        boolean wantOpponent = opponentAppleCooldowns.get() && isOpponentAppleTrackingEnabled();
665
        if (!wantNameplate && !wantMainHand && !wantSlots && !wantEffects && !wantOpponent) return;
666
667
        boolean hasUnlimited = false;
668
        double maxCutoff = 0.0;
669
        if (wantNameplate || wantMainHand) {
670
            if (usesDistanceCutoff("nameplate")) {
671
                maxCutoff = Math.max(maxCutoff, plateDistance.get());
672
            } else {
673
                hasUnlimited = true;
674
            }
675
        }
676
        if (wantSlots) {
677
            if (usesDistanceCutoff("slots")) {
678
                maxCutoff = Math.max(maxCutoff, slotsDistance.get());
679
            } else {
680
                hasUnlimited = true;
681
            }
682
        }
683
        if (wantEffects) {
684
            if (usesDistanceCutoff("effects")) {
685
                maxCutoff = Math.max(maxCutoff, effectsDistance.get());
686
            } else {
687
                hasUnlimited = true;
688
            }
689
        }
690
        if (wantOpponent) {
691
            double oppCutoff = OPPONENT_DISTANCE;
692
            if (oppCutoff > 0) {
693
                maxCutoff = Math.max(maxCutoff, oppCutoff);
694
            } else {
695
                hasUnlimited = true;
696
            }
697
        }
698
699
        Vec3 cameraPos = null;
700
        if (mc.gameRenderer != null && mc.gameRenderer.mainCamera() != null) {
701
            cameraPos = mc.gameRenderer.mainCamera().position();
702
        }
703
        if (cameraPos == null && mc.player != null) {
704
            cameraPos = mc.player.position();
705
        }
706
707
        for (Player player : mc.level.players()) {
708
            if (!shouldRender(player)) continue;
709
            playerBuffer.add(player);
710
            seenIds.add(player.getUUID());
711
        }
712
713
        if (cameraPos != null && playerBuffer.size() > 1) {
714
            double camX = cameraPos.x;
715
            double camY = cameraPos.y;
716
            double camZ = cameraPos.z;
717
            playerBuffer.sort(Comparator.comparingDouble((Player p) -> p.distanceToSqr(camX, camY, camZ)).reversed());
718
        }
719
720
        for (Player player : playerBuffer) {
721
            Vec3 pos = obtainEntityLerpedPos(player, tickDelta);
722
            double dist = (cameraPos == null) ? 0.0 : cameraPos.distanceTo(pos);
723
            if (!hasUnlimited && maxCutoff > 0.0 && dist > maxCutoff) continue;
724
            float presentationAlpha = resolvePresentation(dist).screenAlpha();
725
            if (presentationAlpha <= 0.001f) continue;
726
727
            AABB baseBox = player.getBoundingBox().move(pos.subtract(player.position()));
728
            AABB box = new AABB(
729
                    baseBox.minX, baseBox.minY, baseBox.minZ,
730
                    baseBox.maxX, baseBox.maxY + ESP_REFERENCE_TOP_OFFSET, baseBox.maxZ
731
            );
732
            Vec3 anchor = new Vec3(box.getCenter().x, box.maxY + 0.5, box.getCenter().z);
733
            ScreenRect rect = projectBoxScreen(box, tickDelta);
734
            int centerX;
735
            int anchorY;
736
            if (rect != null) {
737
                centerX = (int) Math.round((rect.minX + rect.maxX) * 0.5);
738
                anchorY = (int) Math.round(rect.minY);
739
            } else {
740
                Vec3 screen = ScreenProjection.worldToScreen(anchor, tickDelta);
741
                if (screen == null) continue;
742
                centerX = (int) screen.x;
743
                anchorY = (int) screen.y;
744
            }
745
            int nameY = computeNameY(rect, anchorY);
746
747
            boolean renderSlots = wantSlots;
748
            if (renderSlots && usesDistanceCutoff("slots") && dist > slotsDistance.get()) renderSlots = false;
749
750
            boolean renderNameplate = wantNameplate;
751
            if (renderNameplate && usesDistanceCutoff("nameplate") && dist > plateDistance.get())
752
                renderNameplate = false;
753
754
            boolean renderEffects = wantEffects;
755
            if (renderEffects && usesDistanceCutoff("effects") && dist > effectsDistance.get()) renderEffects = false;
756
757
            TotemPopSnapshot totemPopSnapshot = TotemPopCounter.snapshot(player.getUUID());
758
            float totemPopAnimation = advanceTotemAnimationHere
759
                    ? updateTotemPopAnimation(player, totemPopSnapshot, dt)
760
                    : totemPopAnimations.getOrDefault(player.getUUID(), totemPopSnapshot.visible() ? 1.0f : 0.0f);
761
            int totemPopCount = resolveTotemPopCount(player, totemPopSnapshot, totemPopAnimation);
762
763
            LabelInfo labelInfo = renderNameplate ? buildLabelInfo(player) : null;
764
            int infoColor = labelInfo != null ? labelInfo.infoColor() : INFO_COLOR_DEFAULT;
765
            TextRenderer nameRenderer = cachedNameTr != null ? cachedNameTr : textRenderer;
766
            TextRenderer hpRenderer = cachedHpTr != null ? cachedHpTr : textRenderer;
767
            NameplateLayout nameplateLayout = null;
768
            MainHandLayout mainHandLayout = null;
769
            boolean renderMainHand = wantMainHand
770
                    && (!usesDistanceCutoff("nameplate") || dist <= plateDistance.get())
771
                    && !player.getMainHandItem().isEmpty();
772
            ItemStack mainHand = renderMainHand ? player.getMainHandItem().copy() : ItemStack.EMPTY;
773
            if (renderNameplate && labelInfo != null) {
774
                nameplateLayout = buildNameplateLayout(
775
                        player, nameRenderer, hpRenderer, labelInfo, dist, centerX, nameY,
776
                        totemPopCount, totemPopAnimation, false
777
                );
778
            }
779
            if (renderMainHand && rect != null) {
780
                mainHandLayout = buildMainHandLayout(
781
                        nameRenderer, mainHand, centerX, (float) rect.maxY + FRAME_CONTENT_GAP, false
782
                );
783
            }
784
785
            ItemStack[] slots = renderSlots ? getCachedEquipmentSlots(player) : EMPTY_SLOTS;
786
            List<List<EnchantLine>> enchantLines = List.of();
787
            int maxEnchantLines = 0;
788
            if (renderSlots) {
789
                EnchantCache cache = resolveEnchantCache(player, slots);
790
                enchantLines = cache.lines;
791
                maxEnchantLines = cache.maxLines;
792
            }
793
            List<MobEffectInstance> effects = renderEffects ? resolveEffects(player) : List.of();
794
795
            int itemsY = computeItemsY(rect, nameplateLayout, nameY);
796
            renderQueue.add(new RenderEntry(player, dist, centerX, nameY, itemsY,
797
                    renderSlots, renderNameplate, renderEffects, labelInfo, infoColor, nameplateLayout,
798
                    mainHand, mainHandLayout,
799
                    slots, enchantLines, maxEnchantLines, effects, totemPopCount, totemPopAnimation,
800
                    presentationAlpha));
801
        }
802
803
        pruneCaches();
804
    }
805
806
    @Override
807
    public void onRenderHudEngineForeground(Renderer2D renderer, TextRenderer textRenderer, GuiGraphicsExtractor ctx, float tickDelta) {
808
        if (!isEnabled() || mc.level == null || mc.player == null) return;
809
810
        ensureFontCache(textRenderer);
811
812
        for (RenderEntry entry : renderQueue) {
813
            renderNameTagForeground(renderer, ctx, textRenderer, entry);
814
        }
815
    }
816
817
    private boolean usesDistanceCutoff(String section) {
818
        return limitDistance.get() && distanceToggles.get(section);
819
    }
820
821
    private boolean shouldRender(Player player) {
822
        if (player == null || mc.player == null) return false;
823
        if (player == mc.player) {
824
            CameraType p = mc.options.getCameraType();
825
            if (p == null || p.isFirstPerson()) return false;
826
            if (!toggles.get("Show self in 3rd person")) return false;
827
        }
828
        String name = player.getGameProfile().name();
829
        return !"FreeCamera".equals(name);
830
    }
831
832
    private int computeNameY(ScreenRect rect, int anchorY) {
833
        float frameTop = rect != null ? (float) rect.minY : anchorY;
834
        return Math.round(frameTop - FRAME_CONTENT_GAP - RICH_TEXT_LOGICAL_HEIGHT - NAMEPLATE_PAD_Y);
835
    }
836
837
    private int computeItemsY(ScreenRect rect, NameplateLayout nameplateLayout, int nameY) {
838
        float nameplateTop = nameplateLayout != null
839
                ? nameplateLayout.bgY()
840
                : nameY - NAMEPLATE_PAD_Y;
841
        return Math.round(nameplateTop - EQUIPMENT_TO_NAMEPLATE_GAP - equipIconSize());
842
    }
843
844
    private WorldUiPresentationService.Snapshot resolvePresentation(double distance) {
845
        WorldUiPresentationService.Mode mode = switch (presentationMode.get()) {
846
            case TWO_D -> WorldUiPresentationService.Mode.SCREEN;
847
            case THREE_D -> WorldUiPresentationService.Mode.WORLD;
848
            case HYBRID -> WorldUiPresentationService.Mode.HYBRID;
849
        };
850
        double projectionYScale = RenderState.worldProjection.m11();
851
        ViewportContext viewport = ViewportContext.current();
852
        double logicalHeight = viewport != null ? viewport.height() : 0.0;
853
        return WorldUiPresentationService.resolve(
854
                mode, distance, WORLD_PRESENTATION_POLICY, projectionYScale, logicalHeight,
855
                worldSize.get(), dynamicWorldScale.get(), dynamicWorldScaleCoefficient.get());
856
    }
857
858
    private void renderWorldNameTag(Renderer3D renderer,
859
                                    WorldBillboardRenderer.Basis basis,
860
                                    WorldRenderEntry entry,
861
                                    ItemBatchRenderer.WorldItemSprite[] itemSprites) {
862
        Player player = entry.player();
863
        TextRenderer nameRenderer = cachedNameTr != null ? cachedNameTr : TextRenderer.get();
864
        TextRenderer hpRenderer = cachedHpTr != null ? cachedHpTr : nameRenderer;
865
        double itemY = -58.0;
866
        NameplateLayout layout = null;
867
868
        if (entry.renderNameplate()) {
869
            LabelInfo info = buildLabelInfo(player);
870
            layout = buildNameplateLayout(
871
                    player,
872
                    nameRenderer,
873
                    hpRenderer,
874
                    info,
875
                    entry.distance(),
876
                    0,
877
                    Math.round(-FRAME_CONTENT_GAP - RICH_TEXT_LOGICAL_HEIGHT - NAMEPLATE_PAD_Y),
878
                    entry.totemPopCount(),
879
                    entry.totemPopAnimation(),
880
                    true
881
            );
882
883
            if (layout != null) {
884
                float materialAlpha = (clampAlpha(nameplateAlpha.get()) / 255.0f) * entry.alpha();
885
                WorldBillboardRenderer.roundedRect(
886
                        renderer, basis, entry.anchor(),
887
                        layout.bgX(), layout.bgY(), layout.bgW(), layout.bgH(),
888
                        MATTE_NAMEPLATE_RADIUS, entry.worldScale(),
889
                        withAlpha(REFERENCE_BACKDROP_RGB, Math.round(255.0f * materialAlpha))
890
                );
891
892
                drawWorldNameplateHead(renderer, basis, entry, layout);
893
894
                double cursorX = layout.nameX();
895
                if (!layout.pingText().isEmpty()) {
896
                    drawWorldText(renderer, basis, nameRenderer, layout.pingText(), entry.anchor(),
897
                            cursorX, layout.nameY(), NAMEPLATE_SCALE, entry.worldScale(),
898
                            resolvePingColor(info.ping()), entry.alpha());
899
                    cursorX += layout.pingWidth() + layout.pingGap();
900
                }
901
902
                String prefix = info.pvpPrefix();
903
                if (!prefix.isEmpty()) {
904
                    drawWorldText(renderer, basis, nameRenderer, prefix, entry.anchor(),
905
                            cursorX, layout.nameY(), NAMEPLATE_SCALE, entry.worldScale(),
906
                            pvpPrefixColor.getArgb(), entry.alpha());
907
                    cursorX += worldTextWidth(nameRenderer, prefix, NAMEPLATE_SCALE);
908
                }
909
910
                if (info.styledName() != null) {
911
                    drawWorldStyledText(renderer, basis, nameRenderer, info.styledName(), entry.anchor(),
912
                            cursorX, layout.nameY(), NAMEPLATE_SCALE, entry.worldScale(),
913
                            CategoryService.getColor(player), entry.alpha());
914
                } else {
915
                    drawWorldText(renderer, basis, nameRenderer, info.name(), entry.anchor(),
916
                            cursorX, layout.nameY(), NAMEPLATE_SCALE, entry.worldScale(),
917
                            CategoryService.getColor(player), entry.alpha());
918
                }
919
920
                String hp = formatNameplateHp(info.hp());
921
                if (!hp.isEmpty()) {
922
                    double hpX = layout.nameX()
923
                            + layout.pingWidth() + layout.pingGap()
924
                            + layout.nameWidth() + layout.hpGap();
925
                    drawWorldHealthTag(renderer, basis, hpRenderer, info.hp(), entry.anchor(),
926
                            hpX, layout.nameY(), NAMEPLATE_SCALE, entry.worldScale(),
927
                            info.infoColor(), entry.alpha());
928
                }
929
930
                if (!layout.distText().isEmpty()) {
931
                    double distX = layout.nameX()
932
                            + layout.pingWidth() + layout.pingGap()
933
                            + layout.nameWidth() + layout.hpGap() + layout.hpWidth()
934
                            + (layout.hpWidth() > 0 ? DIST_TEXT_GAP : 0);
935
                    drawWorldText(renderer, basis, nameRenderer, layout.distText(), entry.anchor(),
936
                            distX, layout.nameY(), NAMEPLATE_SCALE, entry.worldScale(),
937
                            0xFFD0D0D0, entry.alpha());
938
                }
939
940
                drawWorldTotemBadge(renderer, basis, entry, layout, itemSprites, hpRenderer);
941
                itemY = -58.0;
942
            }
943
        }
944
945
        if (entry.renderMainHand()) {
946
            drawWorldMainHand(renderer, basis, entry, layout, itemSprites, nameRenderer);
947
        }
948
949
        int iconSize = equipIconSize();
950
        EquipmentLayout equipment = entry.renderSlots()
951
                ? computeEquipmentLayout(
952
                        nameRenderer, entry.slots(), entry.enchantLines(),
953
                        0.0, iconSize, equipIconGap(), SMALL_TEXT_SCALE, true
954
                )
955
                : EquipmentLayout.empty();
956
957
        if (entry.renderSlots()) {
958
            double enchantHeight = WorldTextRenderer.measure(
959
                    nameRenderer, "Ag", SMALL_TEXT_SCALE, false).height() + 1.0;
960
961
            for (int i = 0; i < entry.slots().length; i++) {
962
                ItemStack stack = entry.slots()[i];
963
                if (stack == null || stack.isEmpty()) continue;
964
965
                double itemX = equipment.centers()[i] - iconSize * 0.5;
966
                if (i < itemSprites.length && itemSprites[i] != null) {
967
                    WorldBillboardRenderer.item(
968
                            renderer, basis, entry.anchor(), itemSprites[i],
969
                            itemX, itemY, iconSize, entry.worldScale(), entry.alpha()
970
                    );
971
                }
972
973
                List<EnchantLine> lines = i < entry.enchantLines().size()
974
                        ? entry.enchantLines().get(i)
975
                        : List.of();
976
                for (int lineIndex = 0; lineIndex < lines.size(); lineIndex++) {
977
                    EnchantLine line = lines.get(lineIndex);
978
                    double width = worldTextWidth(nameRenderer, line.text(), SMALL_TEXT_SCALE);
979
                    double lineY = itemY - 3.0 - enchantHeight * (lineIndex + 1);
980
                    drawWorldText(renderer, basis, nameRenderer, line.text(), entry.anchor(),
981
                            equipment.centers()[i] - width * 0.5, lineY,
982
                            SMALL_TEXT_SCALE, entry.worldScale(), line.color(), entry.alpha(), true);
983
                }
984
            }
985
        }
986
987
        if (entry.renderEffects() && !entry.effects().isEmpty()) {
988
            drawWorldEffects(renderer, basis, entry, itemY, nameRenderer);
989
        }
990
    }
991
992
    private void drawWorldNameplateHead(Renderer3D renderer,
993
                                        WorldBillboardRenderer.Basis basis,
994
                                        WorldRenderEntry entry,
995
                                        NameplateLayout layout) {
996
        if (layout == null || !layout.renderHead()) return;
997
        if (!(entry.player() instanceof AbstractClientPlayer clientPlayer)) return;
998
999
        Identifier skin = PlayerSkinResolver.resolvePlayerSkin(clientPlayer);
1000
        if (skin == null) return;
1001
1002
        float alpha = (clampAlpha(nameplateAlpha.get()) / 255.0f) * entry.alpha();
1003
        if (alpha <= 0.001f) return;
1004
1005
        double inset = layout.headSize() * 0.06;
1006
        double x = layout.headX() + inset;
1007
        double y = layout.headY() + inset;
1008
        double size = Math.max(1.0, layout.headSize() - inset * 2.0);
1009
1010
        WorldBillboardRenderer.texture(
1011
                renderer, basis, entry.anchor(), skin,
1012
                x, y, size, size,
1013
                8f / 64f, 8f / 64f, 16f / 64f, 16f / 64f,
1014
                entry.worldScale(), 0xFFFFFFFF, alpha
1015
        );
1016
        WorldBillboardRenderer.texture(
1017
                renderer, basis, entry.anchor(), skin,
1018
                x, y, size, size,
1019
                40f / 64f, 8f / 64f, 48f / 64f, 16f / 64f,
1020
                entry.worldScale(), 0xFFFFFFFF, alpha
1021
        );
1022
1023
        WorldBillboardRenderer.quad(
1024
                renderer, basis, entry.anchor(),
1025
                layout.dividerX(), layout.dividerY(), layout.dividerW(), layout.dividerH(),
1026
                entry.worldScale(),
1027
                withAlpha(REFERENCE_DIVIDER_RGB, Math.round(REFERENCE_DIVIDER_ALPHA * alpha))
1028
        );
1029
    }
1030
1031
    private void drawWorldTotemBadge(Renderer3D renderer,
1032
                                     WorldBillboardRenderer.Basis basis,
1033
                                     WorldRenderEntry entry,
1034
                                     NameplateLayout layout,
1035
                                     ItemBatchRenderer.WorldItemSprite[] itemSprites,
1036
                                     TextRenderer fallbackRenderer) {
1037
        if (layout == null || !layout.renderTotemBadge()) return;
1038
        if (entry.totemPopCount() <= 0 || entry.totemPopAnimation() <= 0.001f) return;
1039
1040
        float anim = AnimationUtility.easeInOutCubic(entry.totemPopAnimation());
1041
        float materialAlpha = (clampAlpha(nameplateAlpha.get()) / 255.0f) * anim * entry.alpha();
1042
        if (materialAlpha <= 0.001f) return;
1043
1044
        WorldBillboardRenderer.quad(
1045
                renderer, basis, entry.anchor(),
1046
                layout.totemDividerX(), layout.totemDividerY(),
1047
                layout.totemDividerW(), layout.totemDividerH(), entry.worldScale(),
1048
                withAlpha(REFERENCE_DIVIDER_RGB, Math.round(REFERENCE_DIVIDER_ALPHA * materialAlpha))
1049
        );
1050
1051
        double iconScale = 0.86 + 0.14 * anim;
1052
        double iconSize = Math.max(1.0, layout.totemIconSize() * iconScale);
1053
        double iconX = layout.totemBadgeX();
1054
        double iconY = layout.totemBadgeY() + (layout.totemBadgeH() - iconSize) * 0.5;
1055
        int spriteIndex = entry.slots().length;
1056
        if (spriteIndex < itemSprites.length && itemSprites[spriteIndex] != null) {
1057
            WorldBillboardRenderer.item(
1058
                    renderer, basis, entry.anchor(), itemSprites[spriteIndex],
1059
                    iconX, iconY, iconSize, entry.worldScale(), entry.alpha() * anim
1060
            );
1061
        }
1062
1063
        String text = "x" + entry.totemPopCount();
1064
        TextRenderer badgeRenderer = BuiltinFontCatalog.INTER_MEDIUM.renderer(fallbackRenderer);
1065
        double textScale = TOTEM_BADGE_TEXT_SCALE * (0.94 + 0.06 * anim);
1066
        double textX = iconX + iconSize + TOTEM_BADGE_TEXT_GAP;
1067
        double textH = WorldTextRenderer.measure(badgeRenderer, "Ag", textScale, false).height();
1068
        double textY = layout.totemBadgeY() + (layout.totemBadgeH() - textH) * 0.5 - 0.1;
1069
        int textColor = withAlpha(0xFFFFFF, Math.round(255.0f * materialAlpha));
1070
        drawWorldText(
1071
                renderer, basis, badgeRenderer, text, entry.anchor(),
1072
                textX, textY, textScale, entry.worldScale(), textColor, 1.0f
1073
        );
1074
    }
1075
1076
    private void drawWorldMainHand(Renderer3D renderer,
1077
                                   WorldBillboardRenderer.Basis basis,
1078
                                   WorldRenderEntry entry,
1079
                                   NameplateLayout nameplate,
1080
                                   ItemBatchRenderer.WorldItemSprite[] itemSprites,
1081
                                   TextRenderer textRenderer) {
1082
        if (renderer == null || basis == null || entry == null
1083
                || !entry.renderMainHand() || entry.mainHand() == null || entry.mainHand().isEmpty()) {
1084
            return;
1085
        }
1086
        MainHandLayout layout = buildMainHandLayout(
1087
                textRenderer, entry.mainHand(), 0, FRAME_CONTENT_GAP, true
1088
        );
1089
        if (layout == null) return;
1090
        float alpha = (clampAlpha(nameplateAlpha.get()) / 255.0f) * entry.alpha();
1091
        if (alpha <= 0.001f) return;
1092
1093
        WorldBillboardRenderer.roundedRect(
1094
                renderer, basis, entry.bottomAnchor(),
1095
                layout.x(), layout.y(), layout.width(), layout.height(), MAIN_HAND_RADIUS, entry.worldScale(),
1096
                withAlpha(REFERENCE_BACKDROP_RGB, Math.round(255.0f * alpha))
1097
        );
1098
1099
        int spriteIndex = entry.slots().length;
1100
        if (nameplate != null && nameplate.renderTotemBadge()) spriteIndex++;
1101
        if (spriteIndex < itemSprites.length && itemSprites[spriteIndex] != null) {
1102
            WorldBillboardRenderer.item(renderer, basis, entry.bottomAnchor(), itemSprites[spriteIndex],
1103
                    layout.iconX(), layout.iconY(), layout.iconSize(), entry.worldScale(), entry.alpha());
1104
        }
1105
        drawWorldStyledText(renderer, basis, textRenderer, layout.text(), entry.bottomAnchor(),
1106
                layout.textX(), layout.textY(), layout.textScale(), entry.worldScale(),
1107
                resolveItemRarityColor(entry.mainHand()), entry.alpha());
1108
    }
1109
1110
    private void drawWorldEffects(Renderer3D renderer,
1111
                                  WorldBillboardRenderer.Basis basis,
1112
                                  WorldRenderEntry entry,
1113
                                  double itemY,
1114
                                  TextRenderer fallbackRenderer) {
1115
        TextureAtlas atlas = mc.getAtlasManager().getAtlasOrThrow(AtlasIds.GUI);
1116
        if (atlas == null || atlas.location() == null) return;
1117
1118
        int count = entry.effects().size();
1119
        int iconSize = scaleRow(ICON_SIZE);
1120
        int gap = scaleRow(EFFECT_ROW_ICON_GAP);
1121
        int rowGap = scaleRow(EFFECT_ROW_GAP);
1122
        int rowWidth = count * iconSize + Math.max(0, count - 1) * gap;
1123
        double startX = -rowWidth * 0.5;
1124
        int enchantLift = entry.renderSlots()
1125
                ? scaleRow(computeEnchantLift(fallbackRenderer, entry.maxEnchantLines()))
1126
                : 0;
1127
        double iconY = itemY - iconSize - rowGap - enchantLift;
1128
1129
        TextRenderer levelRenderer = cachedLevelTr != null ? cachedLevelTr : fallbackRenderer;
1130
        TextRenderer timeRenderer = cachedTimeTr != null ? cachedTimeTr : fallbackRenderer;
1131
        double rowTextScale = SMALL_TEXT_SCALE * EFFECT_ROW_SCALE;
1132
        double levelHeight = WorldTextRenderer.measure(levelRenderer, "Ag", rowTextScale, false).height();
1133
        double timeHeight = WorldTextRenderer.measure(timeRenderer, "Ag", rowTextScale, false).height();
1134
        int levelGap = scaleRow(EFFECT_ROW_LEVEL_GAP);
1135
        int timeGap = scaleRow(EFFECT_ROW_TIME_GAP);
1136
1137
        for (int i = 0; i < count; i++) {
1138
            MobEffectInstance effect = entry.effects().get(i);
1139
            Identifier spriteId = Hud.getMobEffectSprite(effect.getEffect());
1140
            TextureAtlasSprite sprite = spriteId != null ? atlas.getSprite(spriteId) : null;
1141
            double iconX = startX + i * (iconSize + gap);
1142
1143
            if (sprite != null) {
1144
                WorldBillboardRenderer.texture(
1145
                        renderer, basis, entry.anchor(), atlas.location(),
1146
                        iconX, iconY, iconSize, iconSize,
1147
                        sprite.getU0(), sprite.getV0(), sprite.getU1(), sprite.getV1(),
1148
                        entry.worldScale(), 0xFFFFFFFF, entry.alpha()
1149
                );
1150
            }
1151
1152
            int level = effect.getAmplifier() + 1;
1153
            String duration = formatDuration(entry.player().getId(), effect);
1154
            if (!duration.isEmpty()) {
1155
                double width = worldTextWidth(timeRenderer, duration, rowTextScale);
1156
                double y = level > 1
1157
                        ? iconY - levelHeight - levelGap - timeHeight - timeGap
1158
                        : iconY - timeHeight - levelGap;
1159
                drawWorldText(
1160
                        renderer, basis, timeRenderer, duration, entry.anchor(),
1161
                        iconX + (iconSize - width) * 0.5, y,
1162
                        rowTextScale, entry.worldScale(), EFFECT_TIME_COLOR, entry.alpha()
1163
                );
1164
            }
1165
1166
            if (level > 1) {
1167
                String levelText = roman(level);
1168
                double width = worldTextWidth(levelRenderer, levelText, rowTextScale);
1169
                drawWorldText(
1170
                        renderer, basis, levelRenderer, levelText, entry.anchor(),
1171
                        iconX + (iconSize - width) * 0.5, iconY - levelHeight - levelGap,
1172
                        rowTextScale, entry.worldScale(), EFFECT_LEVEL_STACK_COLOR, entry.alpha()
1173
                );
1174
            }
1175
        }
1176
    }
1177
1178
    private static double worldTextWidth(TextRenderer renderer, String text, double scale) {
1179
        if (text == null || text.isEmpty()) return 0.0;
1180
        return WorldTextRenderer.measure(renderer, text, scale, false).width();
1181
    }
1182
1183
    private static double layoutTextWidth(TextRenderer renderer, String text, double scale, boolean worldText) {
1184
        return worldText
1185
                ? worldTextWidth(renderer, RuntimeTextLayout.singleLine(text), scale)
1186
                : RuntimeTextLayout.width(renderer, text, scale, false);
1187
    }
1188
1189
    private static double layoutTextHeight(TextRenderer renderer, double scale, boolean worldText) {
1190
        return worldText
1191
                ? WorldTextRenderer.measure(renderer, "Ag", scale, false).height()
1192
                : RuntimeTextLayout.height(renderer, scale, false);
1193
    }
1194
1195
    private static double layoutStyledTextWidth(TextRenderer renderer,
1196
                                                Component text,
1197
                                                double scale,
1198
                                                int defaultColor,
1199
                                                boolean worldText) {
1200
        if (text == null) return 0.0;
1201
        double width = 0.0;
1202
        for (TextRenderUtil.Part part : TextRenderUtil.flattenStyled(text, defaultColor)) {
1203
            width += layoutTextWidth(renderer, part.text(), scale, worldText);
1204
        }
1205
        return width;
1206
    }
1207
1208
    private static void drawWorldText(Renderer3D renderer,
1209
                                      WorldBillboardRenderer.Basis basis,
1210
                                      TextRenderer textRenderer,
1211
                                      String text,
1212
                                      Vec3 anchor,
1213
                                      double pixelX,
1214
                                      double pixelY,
1215
                                      double textScale,
1216
                                      double worldScale,
1217
                                      int argb,
1218
                                      float alpha) {
1219
        drawWorldText(renderer, basis, textRenderer, text, anchor, pixelX, pixelY,
1220
                textScale, worldScale, argb, alpha, false);
1221
    }
1222
1223
    private static void drawWorldText(Renderer3D renderer,
1224
                                      WorldBillboardRenderer.Basis basis,
1225
                                      TextRenderer textRenderer,
1226
                                      String text,
1227
                                      Vec3 anchor,
1228
                                      double pixelX,
1229
                                      double pixelY,
1230
                                      double textScale,
1231
                                      double worldScale,
1232
                                      int argb,
1233
                                      float alpha,
1234
                                      boolean shadow) {
1235
        if (text == null || text.isEmpty() || alpha <= 0.001f) return;
1236
        WorldBillboardRenderer.text(renderer, basis, textRenderer, text, anchor, pixelX, pixelY,
1237
                textScale, worldScale, argb, alpha, shadow);
1238
    }
1239
1240
    private static double drawWorldStyledText(Renderer3D renderer,
1241
                                              WorldBillboardRenderer.Basis basis,
1242
                                              TextRenderer textRenderer,
1243
                                              Component text,
1244
                                              Vec3 anchor,
1245
                                              double pixelX,
1246
                                              double pixelY,
1247
                                              double textScale,
1248
                                              double worldScale,
1249
                                              int defaultColor,
1250
                                              float alpha) {
1251
        double cursor = pixelX;
1252
        if (text == null) return cursor;
1253
        for (TextRenderUtil.Part part : TextRenderUtil.flattenStyled(text, defaultColor)) {
1254
            drawWorldText(renderer, basis, textRenderer, part.text(), anchor, cursor, pixelY,
1255
                    textScale, worldScale, part.color(), alpha);
1256
            cursor += worldTextWidth(textRenderer, part.text(), textScale);
1257
        }
1258
        return cursor;
1259
    }
1260
1261
    private void drawNameplateBackground(Renderer2D renderer, Player player, NameplateLayout layout) {
1262
        if (layout == null) return;
1263
        int alpha = Math.round(clampAlpha(nameplateAlpha.get()) * foregroundAlpha);
1264
        if (alpha <= 0) return;
1265
        renderer.roundedRect(
1266
                layout.bgX(), layout.bgY(), layout.bgW(), layout.bgH(),
1267
                MATTE_NAMEPLATE_RADIUS, 0.0f, withAlpha(REFERENCE_BACKDROP_RGB, alpha)
1268
        );
1269
    }
1270
1271
    private float nameplateRadius(NameplateLayout layout) {
1272
        return MATTE_NAMEPLATE_RADIUS;
1273
    }
1274
1275
    private boolean shouldRenderPlayerHead(Player player) {
1276
        return playerHead.get() && player instanceof AbstractClientPlayer;
1277
    }
1278
1279
    private NameplateLayout buildNameplateLayout(Player player, TextRenderer nameRenderer, TextRenderer hpRenderer, LabelInfo info,
1280
                                                 double dist, int centerX, int nameY,
1281
                                                 int totemPopCount, float totemPopAnimation,
1282
                                                 boolean worldText) {
1283
        if (info == null) return null;
1284
        float labelScale = NAMEPLATE_SCALE;
1285
        String prefix = info.pvpPrefix();
1286
        String name = info.name();
1287
        String hp = formatNameplateHp(info.hp());
1288
        String pingText = info.pingText();
1289
        int pingWidth = pingText.isEmpty() ? 0 : (int) Math.ceil(layoutTextWidth(nameRenderer, pingText, labelScale, worldText));
1290
        int pingGap = pingWidth > 0 ? PING_TEXT_GAP : 0;
1291
        double prefixWidth = prefix.isEmpty() ? 0.0 : layoutTextWidth(nameRenderer, prefix, labelScale, worldText);
1292
        double rawNameWidth = info.styledName() != null
1293
                ? layoutStyledTextWidth(nameRenderer, info.styledName(), labelScale, CategoryService.getColor(player), worldText)
1294
                : layoutTextWidth(nameRenderer, name, labelScale, worldText);
1295
        int nameWidth = (int) Math.ceil(prefixWidth + rawNameWidth);
1296
        int hpWidth = hp == null || hp.isEmpty() ? 0 : (int) Math.ceil(layoutTextWidth(hpRenderer, hp, labelScale, worldText));
1297
        int hpGap = hpWidth > 0 ? HP_TEXT_GAP : 0;
1298
        boolean showDist = shouldShowDistanceText(player);
1299
        String distText = showDist ? (int) Math.round(dist) + "m" : "";
1300
        int distWidth = showDist ? (int) Math.ceil(layoutTextWidth(nameRenderer, distText, labelScale, worldText)) : 0;
1301
        int distGap = distWidth > 0 ? DIST_TEXT_GAP : 0;
1302
        float measuredNameHeight = (float) Math.max(
1303
                layoutTextHeight(nameRenderer, labelScale, worldText),
1304
                layoutTextHeight(hpRenderer, labelScale, worldText));
1305
        float visualTextHeight = Math.max(RICH_TEXT_LOGICAL_HEIGHT, measuredNameHeight);
1306
        int nameHeight = Math.max(1, Math.round(visualTextHeight));
1307
        int centeredTextY = Math.round(nameY + (visualTextHeight - measuredNameHeight) * 0.5f);
1308
        boolean renderHead = shouldRenderPlayerHead(player);
1309
        float headSize = renderHead ? Math.max(MATTE_HEAD_MIN_SIZE, nameHeight + NAMEPLATE_PAD_Y * 1.5f) : 0.0f;
1310
        float headBlock = renderHead
1311
                ? headSize + MATTE_HEAD_DIVIDER_GAP + MATTE_HEAD_DIVIDER_WIDTH + MATTE_HEAD_TEXT_GAP
1312
                : 0.0f;
1313
        int textWidth = pingWidth + pingGap + nameWidth + hpGap + hpWidth + distGap + distWidth;
1314
        int scaledHeight = Math.max(nameHeight, renderHead ? Math.round(headSize) : nameHeight);
1315
        float visualHeight = Math.max(visualTextHeight, renderHead ? headSize : visualTextHeight);
1316
        boolean renderTotemBadge = totemPopCounter.get() && totemPopCount > 0 && totemPopAnimation > 0.001f;
1317
        String totemText = renderTotemBadge ? "x" + totemPopCount : "";
1318
        float totemIconSize = renderTotemBadge
1319
                ? Math.min(TOTEM_BADGE_ICON_SIZE, Math.max(8.0f, scaledHeight - 2.0f))
1320
                : 0.0f;
1321
        float totemTextWidth = renderTotemBadge
1322
                ? (float) layoutTextWidth(hpRenderer, totemText, TOTEM_BADGE_TEXT_SCALE, worldText)
1323
                : 0.0f;
1324
        float totemBadgeHeight = renderTotemBadge ? scaledHeight : 0.0f;
1325
        float totemBadgeWidth = renderTotemBadge
1326
                ? totemIconSize + TOTEM_BADGE_TEXT_GAP + totemTextWidth
1327
                : 0.0f;
1328
        float totemBlock = renderTotemBadge
1329
                ? TOTEM_BADGE_GAP + TOTEM_BADGE_DIVIDER_WIDTH + TOTEM_BADGE_DIVIDER_GAP + totemBadgeWidth
1330
                : 0.0f;
1331
        int totalWidth = Math.round(headBlock + textWidth + totemBlock);
1332
        int scaledWidth = totalWidth;
1333
        int contentX = centerX - scaledWidth / 2;
1334
        int nameX = Math.round(contentX + headBlock);
1335
1336
        float bgX = contentX - NAMEPLATE_PAD_X;
1337
        float bgY = nameY - NAMEPLATE_PAD_Y;
1338
        float bgW = scaledWidth + NAMEPLATE_PAD_X * 2f;
1339
        float bgH = visualHeight + NAMEPLATE_PAD_Y * 2f;
1340
        float headX = contentX;
1341
        float headY = nameY + (visualHeight - headSize) * 0.5f;
1342
        float dividerX = headX + headSize + MATTE_HEAD_DIVIDER_GAP;
1343
        float dividerH = Math.max(3.0f, bgH * 0.48f);
1344
        float dividerY = bgY + (bgH - dividerH) * 0.5f;
1345
        float totemDividerX = renderTotemBadge ? contentX + headBlock + textWidth + TOTEM_BADGE_GAP : 0.0f;
1346
        float totemDividerH = renderTotemBadge ? Math.max(3.0f, bgH * 0.48f) : 0.0f;
1347
        float totemDividerY = renderTotemBadge ? bgY + (bgH - totemDividerH) * 0.5f : 0.0f;
1348
        float totemBadgeX = renderTotemBadge ? totemDividerX + TOTEM_BADGE_DIVIDER_WIDTH + TOTEM_BADGE_DIVIDER_GAP : 0.0f;
1349
        float totemBadgeY = renderTotemBadge ? nameY : 0.0f;
1350
1351
        return new NameplateLayout(nameX, centeredTextY, scaledWidth, scaledHeight, labelScale, pingText, distText, bgX, bgY, bgW, bgH,
1352
                pingWidth, pingGap, nameWidth, hpWidth, hpGap, renderHead, headX, headY, headSize,
1353
                dividerX, dividerY, MATTE_HEAD_DIVIDER_WIDTH, dividerH,
1354
                renderTotemBadge, totemDividerX, totemDividerY, TOTEM_BADGE_DIVIDER_WIDTH, totemDividerH,
1355
                totemBadgeX, totemBadgeY, totemBadgeWidth, totemBadgeHeight, totemIconSize);
1356
    }
1357
1358
    private MainHandLayout buildMainHandLayout(TextRenderer renderer, ItemStack stack, int centerX, float topY,
1359
                                               boolean worldText) {
1360
        if (renderer == null || stack == null || stack.isEmpty()) return null;
1361
        Component text = formatMainHandText(stack);
1362
        float textWidth = (float) layoutStyledTextWidth(
1363
                renderer, text, MAIN_HAND_TEXT_SCALE, resolveItemRarityColor(stack), worldText);
1364
        float measuredTextHeight = (float) layoutTextHeight(renderer, MAIN_HAND_TEXT_SCALE, worldText);
1365
        float contentHeight = Math.max(RICH_TEXT_LOGICAL_HEIGHT, Math.max(measuredTextHeight, MAIN_HAND_ICON_SIZE));
1366
        float height = contentHeight + MAIN_HAND_PAD_Y * 2.0f;
1367
        float width = MAIN_HAND_PAD_X * 2.0f + MAIN_HAND_ICON_SIZE + MAIN_HAND_ICON_GAP + textWidth;
1368
        float x = centerX - width * 0.5f;
1369
        float y = topY;
1370
        float iconX = x + MAIN_HAND_PAD_X;
1371
        float iconY = y + (height - MAIN_HAND_ICON_SIZE) * 0.5f;
1372
        float textX = iconX + MAIN_HAND_ICON_SIZE + MAIN_HAND_ICON_GAP;
1373
        float textY = y + (height - measuredTextHeight) * 0.5f;
1374
        return new MainHandLayout(x, y, width, height, iconX, iconY, MAIN_HAND_ICON_SIZE,
1375
                textX, textY, MAIN_HAND_TEXT_SCALE, text);
1376
    }
1377
1378
    private static Component formatMainHandText(ItemStack stack) {
1379
        if (stack == null || stack.isEmpty()) return Component.empty();
1380
        MutableComponent text = Component.literal(stack.getHoverName().getString());
1381
        if (stack.getCount() > 1) {
1382
            text.append(Component.literal(" [").withStyle(ChatFormatting.WHITE));
1383
            text.append(Component.literal(Integer.toString(stack.getCount())).withStyle(ChatFormatting.RED));
1384
            text.append(Component.literal("x").withStyle(ChatFormatting.GRAY));
1385
            text.append(Component.literal("]").withStyle(ChatFormatting.WHITE));
1386
        }
1387
        return text;
1388
    }
1389
1390
    private static int resolveItemRarityColor(ItemStack stack) {
1391
        if (stack == null || stack.isEmpty()) return 0xFFFFFFFF;
1392
        float[] c = RarityColorUtil.INSTANCE.getRarityColor(stack);
1393
        int r = Math.round(Math.max(0.0f, Math.min(1.0f, c[0])) * 255.0f);
1394
        int g = Math.round(Math.max(0.0f, Math.min(1.0f, c[1])) * 255.0f);
1395
        int b = Math.round(Math.max(0.0f, Math.min(1.0f, c[2])) * 255.0f);
1396
        int a = Math.round(Math.max(0.0f, Math.min(1.0f, c[3])) * 255.0f);
1397
        return (a << 24) | (r << 16) | (g << 8) | b;
1398
    }
1399
1400
    private void drawMainHandChip(Renderer2D renderer, TextRenderer fallbackRenderer, ItemStack stack, MainHandLayout layout) {
1401
        if (renderer == null || layout == null || stack == null || stack.isEmpty()) return;
1402
        int alpha = Math.round(clampAlpha(nameplateAlpha.get()) * foregroundAlpha);
1403
        if (alpha <= 0) return;
1404
        renderer.roundedRect(layout.x(), layout.y(), layout.width(), layout.height(),
1405
                MAIN_HAND_RADIUS, 0.0f, withAlpha(REFERENCE_BACKDROP_RGB, alpha));
1406
        renderer.item(stack, layout.iconX(), layout.iconY(), layout.iconSize() / 16.0f,
1407
                917, Renderer2D.ITEM_OVERLAY_NONE, null);
1408
        TextRenderer tr = cachedNameTr != null ? cachedNameTr : fallbackRenderer;
1409
        boolean started = beginTextRenderer(tr, layout.textScale());
1410
        try {
1411
            double cursor = layout.textX();
1412
            for (TextRenderUtil.Part part : TextRenderUtil.flattenStyled(layout.text(), resolveItemRarityColor(stack))) {
1413
                cursor = tr.render(part.text(), cursor, layout.textY(),
1414
                        new RenderColor(foregroundColor(part.color())), false);
1415
            }
1416
        } finally {
1417
            endTextRenderer(tr, started);
1418
        }
1419
    }
1420
1421
    private void renderNameTagForeground(Renderer2D renderer, GuiGraphicsExtractor ctx, TextRenderer textRenderer, RenderEntry entry) {
1422
        float alpha = Math.max(0.0f, Math.min(1.0f, entry.presentationAlpha()));
1423
        if (alpha <= 0.001f) return;
1424
        double previousRendererAlpha = renderer.getAlpha();
1425
        float previousForegroundAlpha = foregroundAlpha;
1426
        foregroundAlpha = alpha;
1427
        renderer.setAlpha(previousRendererAlpha * alpha);
1428
        try {
1429
            renderNameTagForegroundContent(renderer, ctx, textRenderer, entry);
1430
        } finally {
1431
            renderer.setAlpha(previousRendererAlpha);
1432
            foregroundAlpha = previousForegroundAlpha;
1433
        }
1434
    }
1435
1436
    private void renderNameTagForegroundContent(Renderer2D renderer, GuiGraphicsExtractor ctx, TextRenderer textRenderer, RenderEntry entry) {
1437
        Player player = entry.player();
1438
        int centerX = entry.centerX();
1439
        int nameY = entry.nameY();
1440
        int itemsY = entry.itemsY();
1441
        if (entry.renderNameplate() && entry.nameplateLayout() != null) {
1442
            drawNameplateBackground(renderer, player, entry.nameplateLayout());
1443
            drawNameplateHead(renderer, ctx, player, entry.nameplateLayout());
1444
        }
1445
        if (entry.mainHandLayout() != null && entry.mainHand() != null && !entry.mainHand().isEmpty()) {
1446
            drawMainHandChip(renderer, textRenderer, entry.mainHand(), entry.mainHandLayout());
1447
        }
1448
1449
        final int effectsLift = scaleRow(computeEnchantLift(textRenderer, entry.maxEnchantLines()));
1450
        EquipmentLayout equipmentLayout = entry.renderSlots()
1451
                ? computeEquipmentLayout(textRenderer, entry.slots(), entry.enchantLines(), centerX,
1452
                equipIconSize(), equipIconGap(), SMALL_TEXT_SCALE, false)
1453
                : EquipmentLayout.empty();
1454
1455
        if (entry.renderSlots()) {
1456
            drawEquipmentRow(ctx, entry.player(), entry.slots(), equipmentLayout, itemsY);
1457
        }
1458
1459
        if (entry.renderEffects()) {
1460
            EffectIconRenderer.beginBatch();
1461
            drawEffectsRowIcons(ctx, entry.effects(), centerX, itemsY, effectsLift);
1462
            EffectIconRenderer.endBatch();
1463
        }
1464
1465
        drawOpponentCooldownsStackedIcons(ctx, player, entry.nameplateLayout(), centerX, nameY);
1466
1467
        boolean startedBaseText = beginTextRenderer(textRenderer, SMALL_TEXT_SCALE);
1468
        try {
1469
            if (entry.renderSlots()) {
1470
                drawEquipmentRowText(textRenderer, entry.slots(), entry.enchantLines(), equipmentLayout, itemsY);
1471
            }
1472
1473
            if (entry.renderEffects()) {
1474
                TextRenderer levelTr = cachedLevelTr != null ? cachedLevelTr : textRenderer;
1475
                TextRenderer timeTr = cachedTimeTr != null ? cachedTimeTr : textRenderer;
1476
                drawEffectsRowIconOverlays(textRenderer, levelTr, timeTr, entry.effects(), entry.player().getId(), centerX, itemsY, effectsLift);
1477
            }
1478
1479
            drawOpponentCooldownsStackedText(textRenderer, player, entry.nameplateLayout(), centerX, nameY);
1480
        } finally {
1481
            endTextRenderer(textRenderer, startedBaseText);
1482
        }
1483
1484
        if (entry.renderNameplate() && entry.labelInfo() != null) {
1485
            LabelInfo info = entry.labelInfo();
1486
            NameplateLayout layout = entry.nameplateLayout();
1487
            if (layout != null) {
1488
                TextRenderer nameTr = cachedNameTr != null ? cachedNameTr : textRenderer;
1489
                TextRenderer hpTr = cachedHpTr != null ? cachedHpTr : nameTr;
1490
                boolean clipped = pushNameplateScissor(layout);
1491
                float scale = layout.labelScale();
1492
                double nameX = layout.nameX();
1493
                double nameTextY = layout.nameY();
1494
                boolean startedName = beginTextRenderer(nameTr, scale);
1495
                double cursorX = nameX;
1496
                try {
1497
                    if (!layout.pingText().isEmpty()) {
1498
                        renderNameplateText(nameTr, layout.pingText(), cursorX, nameTextY, resolvePingColor(info.ping()));
1499
                        cursorX += layout.pingWidth() + layout.pingGap();
1500
                    }
1501
                    String prefix = info.pvpPrefix();
1502
                    if (!prefix.isEmpty()) {
1503
                        renderNameplateText(nameTr, prefix, cursorX, nameTextY, pvpPrefixColor.getArgb());
1504
                        cursorX += nameTr.getWidth(prefix);
1505
                    }
1506
                    if (info.styledName() != null) {
1507
                        renderStyledNameplateText(nameTr, info.styledName(), cursorX, nameTextY, CategoryService.getColor(player));
1508
                    } else {
1509
                        renderNameplateText(nameTr, info.name(), cursorX, nameTextY, CategoryService.getColor(player));
1510
                    }
1511
                } finally {
1512
                    endTextRenderer(nameTr, startedName);
1513
                }
1514
1515
                if (!info.hp().isEmpty()) {
1516
                    double hpX = nameX + layout.pingWidth() + layout.pingGap() + layout.nameWidth() + layout.hpGap();
1517
                    boolean startedHp = beginTextRenderer(hpTr, scale);
1518
                    try {
1519
                        renderHealthTag(hpTr, info.hp(), hpX, nameTextY, entry.infoColor());
1520
                    } finally {
1521
                        endTextRenderer(hpTr, startedHp);
1522
                    }
1523
                }
1524
1525
                if (!layout.distText().isEmpty()) {
1526
                    double distX = nameX + layout.pingWidth() + layout.pingGap() + layout.nameWidth() + layout.hpGap() + layout.hpWidth()
1527
                            + (layout.hpWidth() > 0 ? DIST_TEXT_GAP : 0);
1528
                    boolean startedDist = beginTextRenderer(nameTr, scale);
1529
                    try {
1530
                        renderNameplateText(nameTr, layout.distText(), distX, nameTextY, 0xFFD0D0D0);
1531
                    } finally {
1532
                        endTextRenderer(nameTr, startedDist);
1533
                    }
1534
                }
1535
                if (clipped) ScissorFunction.pop();
1536
                drawNameplateTotemBadge(renderer, textRenderer, layout, entry.totemPopCount(), entry.totemPopAnimation());
1537
            }
1538
        }
1539
    }
1540
1541
    private void drawNameplateTotemBadge(Renderer2D renderer,
1542
                                         TextRenderer fallbackRenderer,
1543
                                         NameplateLayout layout,
1544
                                         int count,
1545
                                         float animation) {
1546
        if (renderer == null || layout == null || !layout.renderTotemBadge()) return;
1547
        if (count <= 0 || animation <= 0.001f) return;
1548
1549
        float anim = AnimationUtility.easeInOutCubic(animation);
1550
        float globalAlpha = (clampAlpha(nameplateAlpha.get()) / 255.0f) * anim * foregroundAlpha;
1551
        if (globalAlpha <= 0.001f) return;
1552
1553
        drawNameplateDivider(
1554
                renderer,
1555
                layout.totemDividerX(),
1556
                layout.totemDividerY(),
1557
                layout.totemDividerW(),
1558
                layout.totemDividerH(),
1559
                globalAlpha
1560
        );
1561
1562
        float blockX = layout.totemBadgeX();
1563
        float blockY = layout.totemBadgeY();
1564
        float blockH = layout.totemBadgeH();
1565
        float iconScale = 0.86f + 0.14f * anim;
1566
        float iconSize = Math.max(1.0f, layout.totemIconSize() * iconScale);
1567
        float iconX = blockX;
1568
        float iconY = blockY + (blockH - iconSize) * 0.5f;
1569
        renderer.item(totemBadgeStack(), iconX, iconY, Math.max(0.1f, iconSize / 16.0f), 911, Renderer2D.ITEM_OVERLAY_NONE, null);
1570
1571
        String text = "x" + count;
1572
        TextRenderer badgeRenderer = BuiltinFontCatalog.INTER_MEDIUM.renderer(fallbackRenderer);
1573
        float textScale = TOTEM_BADGE_TEXT_SCALE * (0.94f + 0.06f * anim);
1574
        float textX = iconX + iconSize + TOTEM_BADGE_TEXT_GAP;
1575
        float textH = (float) badgeRenderer.getHeight(false) * textScale;
1576
        float textY = blockY + (blockH - textH) * 0.5f - 0.1f;
1577
        int textColor = withAlpha(0xFFFFFF, Math.round(255.0f * globalAlpha));
1578
1579
        badgeRenderer.begin(textScale, false, false);
1580
        try {
1581
            badgeRenderer.render(text, textX, textY, new RenderColor(textColor), false);
1582
        } finally {
1583
            badgeRenderer.end();
1584
        }
1585
    }
1586
1587
    private void drawNameplateHead(Renderer2D renderer, GuiGraphicsExtractor ctx, Player player, NameplateLayout layout) {
1588
        if (ctx == null || layout == null || !layout.renderHead()) return;
1589
        if (!(player instanceof AbstractClientPlayer clientPlayer)) return;
1590
1591
        int alpha = Math.round(clampAlpha(nameplateAlpha.get()) * foregroundAlpha);
1592
        if (alpha <= 0) return;
1593
        float globalAlpha = alpha / 255.0f;
1594
1595
        PlayerHeadRenderer.drawRounded(
1596
                ctx,
1597
                layout.headX(),
1598
                layout.headY(),
1599
                layout.headSize(),
1600
                Math.min(6.0f, layout.headSize() * 0.48f),
1601
                clientPlayer,
1602
                new RenderColor(withAlpha(0xFFFFFF, alpha)),
1603
                true,
1604
                null,
1605
                0.0f,
1606
                false
1607
        );
1608
1609
        drawNameplateDivider(
1610
                renderer,
1611
                layout.dividerX(),
1612
                layout.dividerY(),
1613
                layout.dividerW(),
1614
                layout.dividerH(),
1615
                globalAlpha
1616
        );
1617
    }
1618
1619
    private void drawNameplateDivider(Renderer2D renderer,
1620
                                      float x,
1621
                                      float y,
1622
                                      float width,
1623
                                      float height,
1624
                                      float globalAlpha) {
1625
        if (renderer == null || width <= 0.0f || height <= 0.0f || globalAlpha <= 0.001f) return;
1626
        float drawWidth = Math.max(0.5f, width);
1627
        renderer.quad(
1628
                x + (width - drawWidth) * 0.5f, y, drawWidth, height,
1629
                withAlpha(REFERENCE_DIVIDER_RGB, Math.round(REFERENCE_DIVIDER_ALPHA * globalAlpha))
1630
        );
1631
    }
1632
1633
    private void ensureFontCache(TextRenderer fallback) {
1634
        cachedNameTr = BuiltinFontCatalog.INTER_MEDIUM.renderer(fallback);
1635
        cachedHpTr = BuiltinFontCatalog.INTER_MEDIUM.renderer(cachedNameTr);
1636
        cachedLevelTr = BuiltinFontCatalog.INTER_MEDIUM.renderer(fallback);
1637
        cachedTimeTr = BuiltinFontCatalog.INTER_MEDIUM.renderer(fallback);
1638
    }
1639
1640
    public void onResourceReload() {
1641
        cachedNameTr = null;
1642
        cachedHpTr = null;
1643
        cachedLevelTr = null;
1644
        cachedTimeTr = null;
1645
        enchantCache.clear();
1646
    }
1647
1648
    private boolean shouldShowDistanceText(Player player) {
1649
        if (!toggles.get("Show distance")) return false;
1650
        if (player == null || mc.player == null) return false;
1651
        if (player != mc.player) return true;
1652
        Freecam freecam = Modules.get(Freecam.class);
1653
        return freecam != null && freecam.isEnabled();
1654
    }
1655
1656
    private ItemStack[] getCachedEquipmentSlots(Player player) {
1657
        UUID id = player.getUUID();
1658
        ItemStack[] slots = slotCache.get(id);
1659
        if (slots == null || slots.length != 5) {
1660
            slots = new ItemStack[5];
1661
            slotCache.put(id, slots);
1662
        }
1663
        slots[0] = player.getItemBySlot(EquipmentSlot.FEET);
1664
        slots[1] = player.getItemBySlot(EquipmentSlot.LEGS);
1665
        slots[2] = player.getItemBySlot(EquipmentSlot.CHEST);
1666
        slots[3] = player.getItemBySlot(EquipmentSlot.HEAD);
1667
        slots[4] = player.getOffhandItem();
1668
        return slots;
1669
    }
1670
1671
    private List<MobEffectInstance> resolveEffects(Player player) {
1672
        UUID id = player.getUUID();
1673
        EffectCache cache = effectCache.computeIfAbsent(id, key -> new EffectCache());
1674
        int tick = player.tickCount;
1675
        if (tick - cache.lastTick >= EFFECT_CACHE_TICKS || cache.effects.isEmpty()) {
1676
            cache.effects = collectEffects(player);
1677
            cache.lastTick = tick;
1678
        }
1679
        return cache.effects;
1680
    }
1681
1682
    private EnchantCache resolveEnchantCache(Player player, ItemStack[] slots) {
1683
        UUID id = player.getUUID();
1684
        EnchantCache cache = enchantCache.computeIfAbsent(id, key -> new EnchantCache());
1685
        int tick = player.tickCount;
1686
        int signature = equipmentSignature(slots);
1687
        if (signature != cache.signature
1688
                || tick - cache.lastTick >= ENCHANT_CACHE_TICKS
1689
                || cache.lines.isEmpty()) {
1690
            List<List<EnchantLine>> lines = buildEnchantLines(slots);
1691
            cache.lines = lines;
1692
            cache.maxLines = maxEnchantLines(lines);
1693
            cache.lastTick = tick;
1694
            cache.signature = signature;
1695
        }
1696
        return cache;
1697
    }
1698
1699
    private float updateTotemPopAnimation(Player player, TotemPopSnapshot snapshot, float dt) {
1700
        if (player == null) return 0.0f;
1701
        UUID id = player.getUUID();
1702
        boolean visible = snapshot != null && snapshot.visible();
1703
        if (visible) {
1704
            totemPopLastCounts.put(id, snapshot.count());
1705
        }
1706
1707
        float current = totemPopAnimations.getOrDefault(id, 0.0f);
1708
        float target = visible ? 1.0f : 0.0f;
1709
        float next = AnimationUtility.approach(current, target, dt, TOTEM_BADGE_ANIM_SPEED);
1710
        next = AnimationUtility.snap(next, target, 0.001f);
1711
1712
        if (next <= 0.001f && !visible) {
1713
            totemPopAnimations.remove(id);
1714
            totemPopLastCounts.remove(id);
1715
            return 0.0f;
1716
        }
1717
1718
        totemPopAnimations.put(id, next);
1719
        return next;
1720
    }
1721
1722
    private int resolveTotemPopCount(Player player, TotemPopSnapshot snapshot, float animation) {
1723
        if (player == null) return 0;
1724
        if (snapshot != null && snapshot.visible()) {
1725
            return snapshot.count();
1726
        }
1727
        if (animation > 0.001f) {
1728
            return Math.max(0, totemPopLastCounts.getOrDefault(player.getUUID(), 0));
1729
        }
1730
        return 0;
1731
    }
1732
1733
    private void pruneCaches() {
1734
        if (seenIds.isEmpty()) {
1735
            slotCache.clear();
1736
            effectCache.clear();
1737
            enchantCache.clear();
1738
            totemPopAnimations.clear();
1739
            totemPopLastCounts.clear();
1740
            return;
1741
        }
1742
        slotCache.keySet().removeIf(id -> !seenIds.contains(id));
1743
        effectCache.keySet().removeIf(id -> !seenIds.contains(id));
1744
        enchantCache.keySet().removeIf(id -> !seenIds.contains(id));
1745
        totemPopAnimations.keySet().removeIf(id -> !seenIds.contains(id));
1746
        totemPopLastCounts.keySet().removeIf(id -> !seenIds.contains(id));
1747
    }
1748
1749
    private void drawEquipmentRow(GuiGraphicsExtractor ctx,
1750
                                  Player player,
1751
                                  ItemStack[] slots,
1752
                                  EquipmentLayout layout,
1753
                                  int y) {
1754
        int iconSize = equipIconSize();
1755
        int seed = 0;
1756
1757
        for (int i = 0; i < slots.length; i++) {
1758
            ItemStack stack = slots[i];
1759
            float x = (float) (layout.centers()[i] - iconSize * 0.5);
1760
            if (stack.isEmpty()) continue;
1761
1762
            float scale = iconSize / 16f;
1763
            int overlayFlags = Renderer2D.ITEM_OVERLAY_COUNT;
1764
            if (toggles.get("Item durability bar")) {
1765
                overlayFlags |= Renderer2D.ITEM_OVERLAY_DURABILITY;
1766
            }
1767
            Renderer2D.COLOR.item(stack, x, y, scale, seed++, overlayFlags, null,
1768
                    durabilityStartPercent.get(), 70);
1769
            drawOpponentItemCooldown(player, stack, x, y, scale);
1770
        }
1771
    }
1772
1773
    private void drawOpponentItemCooldown(Player player, ItemStack stack, float x, float y, float scale) {
1774
        if (!shouldRenderOpponentStuff(player)) return;
1775
        if (stack == null || stack.isEmpty()) return;
1776
1777
        Item item = stack.getItem();
1778
        if (!CooldownRegistry.isTracked(item)) return;
1779
1780
        ItemCooldownSnapshot snapshot = OpponentCooldownManager.snapshot(player.getUUID(), item);
1781
        if (!snapshot.visible()) return;
1782
        float progress = snapshot.cooling() ? snapshot.cooldownProgress() : snapshot.usesProgress();
1783
        if (progress <= 0f) return;
1784
1785
        int top = Mth.floor(16.0F * (1.0F - progress));
1786
        int bottom = top + Mth.ceil(16.0F * progress);
1787
        Renderer2D.COLOR.quad(
1788
                x,
1789
                y + top * scale,
1790
                16.0f * scale,
1791
                (bottom - top) * scale,
1792
                snapshot.cooling() ? 0x80FFA500 : 0x706D9DFF
1793
        );
1794
1795
        // no text inside slot
1796
    }
1797
1798
    private void drawEquipmentRowText(TextRenderer textRenderer, ItemStack[] slots, List<List<EnchantLine>> enchantLines,
1799
                                      EquipmentLayout layout, int y) {
1800
        int iconSize = equipIconSize();
1801
1802
        for (int i = 0; i < slots.length; i++) {
1803
            ItemStack stack = slots[i];
1804
            double center = layout.centers()[i];
1805
            if (stack.isEmpty()) continue;
1806
1807
            List<EnchantLine> ench = enchantLines.get(i);
1808
            if (!ench.isEmpty()) {
1809
                int lineHeight = (int) textRenderer.getHeight(true) + 1;
1810
                int startY = y - 14;
1811
                for (int idx = 0; idx < ench.size(); idx++) {
1812
                    EnchantLine line = ench.get(idx);
1813
                    int lineY = startY - idx * lineHeight;
1814
                    int textX = (int) Math.round(center - textRenderer.getWidth(line.text(), true) * 0.5);
1815
                    renderEquipmentText(textRenderer, line.text(), textX, lineY, line.color());
1816
                }
1817
            }
1818
1819
        }
1820
    }
1821
1822
    private EquipmentLayout computeEquipmentLayout(TextRenderer textRenderer,
1823
                                                    ItemStack[] slots,
1824
                                                    List<List<EnchantLine>> enchantLines,
1825
                                                    double centerX,
1826
                                                    int iconSize,
1827
                                                    int requestedGap,
1828
                                                    double enchantTextScale,
1829
                                                    boolean worldText) {
1830
        if (slots == null || slots.length == 0) return EquipmentLayout.empty();
1831
        double[] widths = new double[slots.length];
1832
        double totalWidth = 0.0;
1833
        double gap = Math.max(ENCHANT_TEXT_MIN_GAP, requestedGap);
1834
        for (int i = 0; i < slots.length; i++) {
1835
            double columnWidth = iconSize;
1836
            List<EnchantLine> lines = enchantLines != null && i < enchantLines.size()
1837
                    ? enchantLines.get(i)
1838
                    : List.of();
1839
            for (EnchantLine line : lines) {
1840
                double textWidth = worldText
1841
                        ? worldTextWidth(textRenderer, RuntimeTextLayout.singleLine(line.text()), enchantTextScale) + 1.0
1842
                        : RuntimeTextLayout.width(textRenderer, line.text(), enchantTextScale, true);
1843
                columnWidth = Math.max(columnWidth,
1844
                        textWidth);
1845
            }
1846
            widths[i] = columnWidth;
1847
            totalWidth += columnWidth;
1848
        }
1849
        totalWidth += Math.max(0, slots.length - 1) * gap;
1850
1851
        double[] centers = new double[slots.length];
1852
        double cursor = centerX - totalWidth * 0.5;
1853
        for (int i = 0; i < widths.length; i++) {
1854
            centers[i] = cursor + widths[i] * 0.5;
1855
            cursor += widths[i] + gap;
1856
        }
1857
        return new EquipmentLayout(centers, totalWidth);
1858
    }
1859
1860
    private int foregroundColor(int argb) {
1861
        return withAlpha(argb, Math.round(((argb >>> 24) & 0xFF) * foregroundAlpha));
1862
    }
1863
1864
    private void renderEquipmentText(TextRenderer textRenderer, String text, double x, double y, int color) {
1865
        textRenderer.render(text, x, y, new RenderColor(foregroundColor(color)), true);
1866
    }
1867
1868
    private void renderHealthTag(TextRenderer textRenderer, String value, double x, double y, int valueColor) {
1869
        if (value == null || value.isEmpty()) return;
1870
        renderNameplateText(textRenderer, "[", x, y, 0xFFFFFFFF);
1871
        double cursor = x + textRenderer.getWidth("[");
1872
        renderNameplateText(textRenderer, value, cursor, y, valueColor);
1873
        cursor += textRenderer.getWidth(value);
1874
        renderNameplateText(textRenderer, "]", cursor, y, 0xFFFFFFFF);
1875
    }
1876
1877
    private static void drawWorldHealthTag(Renderer3D renderer,
1878
                                           WorldBillboardRenderer.Basis basis,
1879
                                           TextRenderer textRenderer,
1880
                                           String value,
1881
                                           Vec3 anchor,
1882
                                           double x,
1883
                                           double y,
1884
                                           double textScale,
1885
                                           double worldScale,
1886
                                           int valueColor,
1887
                                           float alpha) {
1888
        if (value == null || value.isEmpty()) return;
1889
        drawWorldText(renderer, basis, textRenderer, "[", anchor, x, y, textScale, worldScale, 0xFFFFFFFF, alpha);
1890
        double cursor = x + worldTextWidth(textRenderer, "[", textScale);
1891
        drawWorldText(renderer, basis, textRenderer, value, anchor, cursor, y, textScale, worldScale, valueColor, alpha);
1892
        cursor += worldTextWidth(textRenderer, value, textScale);
1893
        drawWorldText(renderer, basis, textRenderer, "]", anchor, cursor, y, textScale, worldScale, 0xFFFFFFFF, alpha);
1894
    }
1895
1896
    private void renderNameplateText(TextRenderer textRenderer, String text, double x, double y, int color) {
1897
        if (text == null || text.isEmpty()) return;
1898
        textRenderer.render(text, x, y, new RenderColor(foregroundColor(color)), false);
1899
    }
1900
1901
    private void renderStyledNameplateText(TextRenderer textRenderer, Component text, double x, double y, int defaultColor) {
1902
        if (text == null) return;
1903
        List<TextRenderUtil.Part> parts = TextRenderUtil.flattenStyled(text, defaultColor);
1904
        double cursorX = x;
1905
        for (TextRenderUtil.Part part : parts) {
1906
            renderNameplateText(textRenderer, part.text(), cursorX, y, part.color());
1907
            cursorX += textRenderer.getWidth(part.text());
1908
        }
1909
    }
1910
1911
    private boolean shouldUseTabNames() {
1912
        return nameplateExtras.get("Tab names");
1913
    }
1914
1915
    private boolean shouldShowPingText() {
1916
        return nameplateExtras.get("Ping");
1917
    }
1918
1919
    private int getPlayerPing(Player player) {
1920
        if (player == null || mc == null || mc.getConnection() == null) return -1;
1921
        PlayerInfo entry = mc.getConnection().getPlayerInfo(player.getUUID());
1922
        return entry != null ? entry.getLatency() : -1;
1923
    }
1924
1925
    private void drawEffectsIcons(GuiGraphicsExtractor ctx, List<MobEffectInstance> effects, int x, int y) {
1926
        if (effects.isEmpty()) return;
1927
1928
        int cursorY = y;
1929
        EffectIconRenderer.beginBatch();
1930
        for (MobEffectInstance inst : effects) {
1931
            EffectIconRenderer.draw(ctx, inst, x, cursorY, ICON_SIZE, foregroundColor(0xFFFFFFFF));
1932
            cursorY += EFFECT_LINE_HEIGHT;
1933
        }
1934
        EffectIconRenderer.endBatch();
1935
    }
1936
1937
    private void drawEffectsText(TextRenderer textRenderer, List<MobEffectInstance> effects, int entityId, int x, int y) {
1938
        if (effects.isEmpty()) return;
1939
1940
        int cursorY = y;
1941
        for (MobEffectInstance inst : effects) {
1942
            int textX = x + ICON_SIZE + 6;
1943
            int textY = cursorY + 4;
1944
            String dur = formatDuration(entityId, inst);
1945
            String name = I18n.get(inst.getEffect().value().getDescriptionId());
1946
            int level = inst.getAmplifier() + 1;
1947
1948
            if (!dur.isEmpty()) {
1949
                String seg = dur + " ";
1950
                textRenderer.render(seg, textX, textY, new RenderColor(foregroundColor(0xFFFFFFFF)), false);
1951
                textX += (int) textRenderer.getWidth(seg, false);
1952
            }
1953
            textRenderer.render(name, textX, textY, new RenderColor(foregroundColor(0xFFFFFFFF)), false);
1954
            textX += (int) textRenderer.getWidth(name, false);
1955
            if (level > 1) {
1956
                String lvl = " " + level;
1957
                textRenderer.render(lvl, textX, textY, new RenderColor(foregroundColor(EFFECT_LEVEL_COLOR)), false);
1958
            }
1959
            cursorY += EFFECT_LINE_HEIGHT;
1960
        }
1961
    }
1962
1963
    private void drawEffectIconOverlays(TextRenderer baseRenderer, TextRenderer levelRenderer, TextRenderer timeRenderer,
1964
                                        List<MobEffectInstance> effects, int entityId, int x, int y) {
1965
        if (effects.isEmpty()) return;
1966
1967
        TextRenderer levelTr = levelRenderer == null ? baseRenderer : levelRenderer;
1968
        TextRenderer timeTr = timeRenderer == null ? baseRenderer : timeRenderer;
1969
1970
        boolean startedLevel = beginTextRenderer(levelTr, SMALL_TEXT_SCALE);
1971
        boolean startedTime = timeTr != levelTr && beginTextRenderer(timeTr, SMALL_TEXT_SCALE);
1972
1973
        int levelHeight = (int) levelTr.getHeight(false);
1974
        int timeHeight = (int) timeTr.getHeight(false);
1975
        int levelGap = scaleRow(EFFECT_ROW_LEVEL_GAP);
1976
        int timeGap = scaleRow(EFFECT_ROW_TIME_GAP);
1977
1978
        int cursorY = y;
1979
        for (MobEffectInstance inst : effects) {
1980
            int level = inst.getAmplifier() + 1;
1981
            String dur = formatDuration(entityId, inst);
1982
1983
            int iconX = x;
1984
            int iconY = cursorY;
1985
1986
            if (!dur.isEmpty()) {
1987
                int timeW = (int) timeTr.getWidth(dur, false);
1988
                int timeX = iconX + (ICON_SIZE - timeW) / 2;
1989
                int timeY = iconY - timeHeight - 1;
1990
                timeTr.render(dur, timeX, timeY, new RenderColor(foregroundColor(EFFECT_TIME_COLOR)), false);
1991
            }
1992
1993
            if (level > 1) {
1994
                String lvl = String.valueOf(level);
1995
                int levelW = (int) levelTr.getWidth(lvl, false);
1996
                int levelX = iconX + (ICON_SIZE - levelW) / 2;
1997
                int levelY = !dur.isEmpty()
1998
                        ? (iconY - timeHeight - 1 - levelHeight - 1)
1999
                        : (iconY - levelHeight - 1);
2000
                levelTr.render(lvl, levelX, levelY, new RenderColor(foregroundColor(EFFECT_LEVEL_STACK_COLOR)), false);
2001
            }
2002
            cursorY += EFFECT_LINE_HEIGHT;
2003
        }
2004
2005
        endTextRenderer(levelTr, startedLevel);
2006
        endTextRenderer(timeTr, startedTime);
2007
    }
2008
2009
    private void drawEffectsRowIconOverlays(TextRenderer baseRenderer, TextRenderer levelRenderer, TextRenderer timeRenderer,
2010
                                            List<MobEffectInstance> effects, int entityId, int centerX, int itemsY, int lift) {
2011
        if (effects.isEmpty()) return;
2012
2013
        TextRenderer levelTr = levelRenderer == null ? baseRenderer : levelRenderer;
2014
        TextRenderer timeTr = timeRenderer == null ? baseRenderer : timeRenderer;
2015
2016
        float rowTextScale = SMALL_TEXT_SCALE * EFFECT_ROW_SCALE;
2017
        boolean startedLevel = beginTextRenderer(levelTr, rowTextScale);
2018
        boolean startedTime = timeTr != levelTr && beginTextRenderer(timeTr, rowTextScale);
2019
2020
        int levelHeight = (int) levelTr.getHeight(false);
2021
        int timeHeight = (int) timeTr.getHeight(false);
2022
        int levelGap = scaleRow(EFFECT_ROW_LEVEL_GAP);
2023
        int timeGap = scaleRow(EFFECT_ROW_TIME_GAP);
2024
2025
        int count = effects.size();
2026
        int iconSize = scaleRow(ICON_SIZE);
2027
        int gap = scaleRow(EFFECT_ROW_ICON_GAP);
2028
        int rowGap = scaleRow(EFFECT_ROW_GAP);
2029
        int rowW = count * iconSize + Math.max(0, count - 1) * gap;
2030
        int startX = centerX - rowW / 2;
2031
        int iconY = itemsY - iconSize - rowGap - lift;
2032
2033
        for (int i = 0; i < effects.size(); i++) {
2034
            MobEffectInstance inst = effects.get(i);
2035
            int level = inst.getAmplifier() + 1;
2036
            String dur = formatDuration(entityId, inst);
2037
2038
            int iconX = startX + i * (iconSize + gap);
2039
2040
            if (!dur.isEmpty()) {
2041
                int timeW = (int) timeTr.getWidth(dur, false);
2042
                int timeX = iconX + (iconSize - timeW) / 2;
2043
                int timeY = (level > 1)
2044
                        ? (iconY - levelHeight - levelGap - timeHeight - timeGap)
2045
                        : (iconY - timeHeight - levelGap);
2046
                timeTr.render(dur, timeX, timeY, new RenderColor(foregroundColor(EFFECT_TIME_COLOR)), false);
2047
            }
2048
2049
            if (level > 1) {
2050
                String lvl = roman(level);
2051
                int levelW = (int) levelTr.getWidth(lvl, false);
2052
                int levelX = iconX + (iconSize - levelW) / 2;
2053
                int levelY = iconY - levelHeight - levelGap;
2054
                levelTr.render(lvl, levelX, levelY, new RenderColor(foregroundColor(EFFECT_LEVEL_STACK_COLOR)), false);
2055
            }
2056
        }
2057
2058
        endTextRenderer(levelTr, startedLevel);
2059
        endTextRenderer(timeTr, startedTime);
2060
    }
2061
2062
    private void drawEffectsRowIcons(GuiGraphicsExtractor ctx, List<MobEffectInstance> effects, int centerX, int itemsY, int lift) {
2063
        if (effects.isEmpty()) return;
2064
        int count = effects.size();
2065
        int iconSize = scaleRow(ICON_SIZE);
2066
        int gap = scaleRow(EFFECT_ROW_ICON_GAP);
2067
        int rowGap = scaleRow(EFFECT_ROW_GAP);
2068
        int rowW = count * iconSize + Math.max(0, count - 1) * gap;
2069
        int startX = centerX - rowW / 2;
2070
        int y = itemsY - iconSize - rowGap - lift;
2071
2072
        for (int i = 0; i < effects.size(); i++) {
2073
            int x = startX + i * (iconSize + gap);
2074
            EffectIconRenderer.draw(ctx, effects.get(i), x, y, iconSize, foregroundColor(0xFFFFFFFF));
2075
        }
2076
    }
2077
2078
    private int computeEnchantLift(TextRenderer textRenderer, int maxLines) {
2079
        if (!toggles.get("Show armor row")) return 0;
2080
        if (maxLines <= 0) return 6;
2081
        int lineHeight = (int) Math.round(textRenderer.getHeight(true) * SMALL_TEXT_SCALE) + 1;
2082
        return 6 + maxLines * lineHeight;
2083
    }
2084
2085
    private LabelInfo buildLabelInfo(Player player) {
2086
        Component styledName = resolveNameplateText(player);
2087
        String name = styledName == null ? "" : styledName.getString();
2088
        String prefix = "";
2089
        if (pvpPrefix.get() && PvpTargetState.isTargetInPvp(player.getUUID())) {
2090
            prefix = "[PVP] ";
2091
        }
2092
        int ping = getPlayerPing(player);
2093
        String pingText = shouldShowPingText() && ping >= 0 ? ping + "ms" : "";
2094
        if (isCreative(player)) {
2095
            return new LabelInfo(prefix, styledName, name, ping, pingText, "GM", PlayerRelations.get().colorStaff());
2096
        }
2097
        PlayerHealthResolver.HealthSnapshot health = PlayerHealthResolver.resolve(player);
2098
        String hp = formatHealth(health.totalHealth());
2099
        int color = HP_RED;
2100
        return new LabelInfo(prefix, styledName, name, ping, pingText, hp, color);
2101
    }
2102
2103
    private Component resolveNameplateText(Player player) {
2104
        if (player == null) return Component.empty();
2105
        String fallback = player.getGameProfile().name();
2106
        if (!shouldUseTabNames()) {
2107
            Component display = player.getDisplayName();
2108
            Component resolved = display != null ? display : Component.literal(fallback);
2109
            Component sanitized = normalizeNameplateComponent(resolved);
2110
            return sanitized.getString().isBlank() ? Component.literal(fallback) : sanitized;
2111
        }
2112
2113
        var handler = mc.getConnection();
2114
        if (handler == null) return Component.literal(fallback);
2115
        PlayerInfo entry = handler.getPlayerInfo(player.getUUID());
2116
        if (entry == null) return Component.literal(fallback);
2117
2118
        Component displayName = entry.getTabListDisplayName();
2119
        if (displayName == null) return Component.literal(fallback);
2120
2121
        Component parsed = normalizeNameplateComponent(displayName);
2122
        if (parsed == null || parsed.getString().isBlank()) return Component.literal(fallback);
2123
        return parsed;
2124
    }
2125
2126
    private static Component normalizeNameplateComponent(Component value) {
2127
        if (value == null) return Component.empty();
2128
        return RuntimeTextLayout.singleLine(LegacyTextUtil.convertLegacyCodesRobust(value));
2129
    }
2130
2131
    private String formatHealth(float hp) {
2132
        if (hpDecimals.get()) {
2133
            return formatTenths(hp);
2134
        }
2135
        int value = (int) Math.ceil(hp);
2136
        return String.valueOf(value);
2137
    }
2138
2139
    private float totalHealth(Player player) {
2140
        return PlayerHealthResolver.resolve(player).totalHealth();
2141
    }
2142
2143
    private float maxTotalHealth(Player player) {
2144
        return PlayerHealthResolver.resolve(player).maxHealth();
2145
    }
2146
2147
    private String formatTenths(float value) {
2148
        int tenth = Math.round(value * 10f);
2149
        int whole = tenth / 10;
2150
        int frac = Math.abs(tenth % 10);
2151
        return whole + "." + frac;
2152
    }
2153
2154
    private int resolveHealthColor(float current, float max) {
2155
        if (current > max) return HP_CYAN;
2156
        if ("Static".equalsIgnoreCase(hpColorMode.get())) {
2157
            return HP_GREEN;
2158
        }
2159
        return gradientHealthColor(current, max);
2160
    }
2161
2162
    private int gradientHealthColor(float current, float max) {
2163
        if (max <= 0f) return HP_RED;
2164
        float clamped = Mth.clamp(current, 0f, max);
2165
        if (max <= 20f) {
2166
            float t = clamped / max;
2167
            return lerpColor(HP_RED, HP_GREEN, t);
2168
        }
2169
        if (clamped <= 20f) {
2170
            float t = clamped / 20f;
2171
            return lerpColor(HP_RED, HP_GREEN, t);
2172
        }
2173
        float t = (clamped - 20f) / (max - 20f);
2174
        return lerpColor(HP_GREEN, HP_CYAN, Mth.clamp(t, 0f, 1f));
2175
    }
2176
2177
    private boolean isCreative(Player player) {
2178
        if (player.isCreative()) return true;
2179
        var handler = mc.getConnection();
2180
        if (handler == null) return false;
2181
        PlayerInfo entry = handler.getPlayerInfo(player.getUUID());
2182
        if (entry == null) return false;
2183
        GameType mode = entry.getGameMode();
2184
        return mode == GameType.CREATIVE;
2185
    }
2186
2187
    private String formatEffectText(int entityId, MobEffectInstance inst) {
2188
        String name = I18n.get(inst.getEffect().value().getDescriptionId());
2189
        int level = inst.getAmplifier() + 1;
2190
        if (level > 1) name = name + " " + level;
2191
        String dur = formatDuration(entityId, inst);
2192
        return dur.isEmpty() ? name : dur + " " + name;
2193
    }
2194
2195
    private String formatDuration(int entityId, MobEffectInstance inst) {
2196
        if (StatusEffectTracker.shouldHideDuration(entityId, inst.getEffect())) return "";
2197
        int ticks = inst.getDuration();
2198
        if (ticks < 0 || ticks >= 32767) return "";
2199
        int totalSeconds = Math.max(0, ticks / 20);
2200
        int minutes = totalSeconds / 60;
2201
        int seconds = totalSeconds % 60;
2202
        if (seconds < 10) return minutes + ":0" + seconds;
2203
        return minutes + ":" + seconds;
2204
    }
2205
2206
    private List<MobEffectInstance> collectEffects(Player player) {
2207
        return StatusEffectView.collectHudEffects(player);
2208
    }
2209
2210
    private String roman(int n) {
2211
        if (n <= 0) return String.valueOf(n);
2212
        int value = n;
2213
        StringBuilder sb = new StringBuilder();
2214
        int[] vals = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
2215
        String[] syms = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
2216
        for (int i = 0; i < vals.length; i++) {
2217
            while (value >= vals[i]) {
2218
                value -= vals[i];
2219
                sb.append(syms[i]);
2220
            }
2221
        }
2222
        return sb.toString();
2223
    }
2224
2225
    private List<EnchantLine> formatEnchantments(ItemStack stack) {
2226
        List<EnchantLine> parts = new ArrayList<>();
2227
2228
        ItemEnchantments enchComp = EnchantmentHelper.getEnchantmentsForCrafting(stack);
2229
        for (Object2IntMap.Entry<Holder<Enchantment>> entry : enchComp.entrySet()) {
2230
            Holder<Enchantment> ref = entry.getKey();
2231
            int level = entry.getIntValue();
2232
            if (level <= 0) continue;
2233
2234
            ResourceKey<Enchantment> key = ref.unwrapKey().orElse(null);
2235
            if (key == null) continue;
2236
2237
            EnchantMeta meta = EnchantRegistry.REGISTRY.get(key);
2238
            if (meta == null) continue;
2239
2240
            Enchantment value = ref.value();
2241
            boolean singleLevel = value.getMaxLevel() == 1;
2242
            boolean overMax = EnchantUtil.isInvalidLevel(ref, level);
2243
            if (!isEnchantEnabled(meta.category(), meta.key())
2244
                    && !(illegalEnchantsAlways.get() && overMax)) {
2245
                continue;
2246
            }
2247
2248
            String shortName = limitCodePoints(meta.shortName(), ENCHANT_NAME_MAX_CODEPOINTS);
2249
            String text = singleLevel && level == 1
2250
                    ? shortName
2251
                    : shortName + level;
2252
2253
            int color = overMax
2254
                    ? IllegalItemUtil.illegalColor()
2255
                    : (level == value.getMaxLevel() ? TopEnchantUtil.topColor() : 0xFFFFFFFF);
2256
2257
            parts.add(new EnchantLine(text, color));
2258
        }
2259
2260
        return parts;
2261
    }
2262
2263
    private static String limitCodePoints(String value, int maxCodePoints) {
2264
        if (value == null || value.isEmpty() || maxCodePoints <= 0) return "";
2265
        int count = value.codePointCount(0, value.length());
2266
        if (count <= maxCodePoints) return value;
2267
        return value.substring(0, value.offsetByCodePoints(0, maxCodePoints));
2268
    }
2269
2270
    private boolean isEnchantEnabled(String category, String path) {
2271
        Map<String, Boolean> map = switch (category) {
2272
            case "armor" -> enchantArmor.get();
2273
            case "melee" -> enchantMelee.get();
2274
            case "tools" -> enchantTools.get();
2275
            case "bow" -> enchantBow.get();
2276
            case "fishing" -> enchantFishing.get();
2277
            case "trident" -> enchantTrident.get();
2278
            case "crossbow" -> enchantCrossbow.get();
2279
            case "mace" -> enchantMace.get();
2280
            default -> enchantOther.get();
2281
        };
2282
        return map.getOrDefault(path, false);
2283
    }
2284
2285
    private boolean shouldRenderOpponentStuff(Player p) {
2286
        if (p == null || mc.player == null) return false;
2287
        if (p == mc.player) return false;
2288
        if (!opponentAppleCooldowns.get()) return false;
2289
        if (!isOpponentAppleTrackingEnabled()) return false;
2290
        if (!PvpTargetState.isTargetInPvp(p.getUUID()) && !hasOpponentCooldowns(p.getUUID())) return false;
2291
        double maxDist = OPPONENT_DISTANCE;
2292
        return !(maxDist > 0) || !(mc.player.distanceToSqr(p) > maxDist * maxDist);
2293
    }
2294
2295
    private boolean isOpponentAppleTrackingEnabled() {
2296
        PvpCooldowns mod = Modules.get(PvpCooldowns.class);
2297
        return mod != null && mod.isSystemEnabled();
2298
    }
2299
2300
    private void drawOpponentCooldownsStackedIcons(GuiGraphicsExtractor ctx, Player player, NameplateLayout layout, int centerX, int nameY) {
2301
        if (!shouldRenderOpponentStuff(player)) return;
2302
2303
        int startX = computeOpponentStackX(layout, centerX);
2304
        int startY = computeOpponentStackY(nameY);
2305
2306
        int y = startY;
2307
        int seed = 0;
2308
        for (Item item : CooldownRegistry.trackedItems()) {
2309
            ItemCooldownSnapshot snapshot = OpponentCooldownManager.snapshot(player.getUUID(), item);
2310
            if (!snapshot.visible()) continue;
2311
2312
            ItemStack icon = new ItemStack(item);
2313
            float scale = ICON_SIZE / 16f;
2314
            Renderer2D.COLOR.item(icon, startX, y, scale, seed++, Renderer2D.ITEM_OVERLAY_NONE, null);
2315
2316
            y += EFFECT_LINE_HEIGHT;
2317
        }
2318
    }
2319
2320
    private void drawOpponentCooldownsStackedText(TextRenderer textRenderer, Player player, NameplateLayout layout, int centerX, int nameY) {
2321
        if (!shouldRenderOpponentStuff(player)) return;
2322
2323
        int startX = computeOpponentStackX(layout, centerX);
2324
        int startY = computeOpponentStackY(nameY);
2325
2326
        int timeColor = PvpTargetState.isTargetInPvp(player.getUUID())
2327
                ? OPP_TIME_COLOR
2328
                : OPP_TIME_COLOR_GRACE;
2329
        int y = startY;
2330
        for (Item item : CooldownRegistry.trackedItems()) {
2331
            ItemCooldownSnapshot snapshot = OpponentCooldownManager.snapshot(player.getUUID(), item);
2332
            if (!snapshot.visible()) continue;
2333
2334
            String prefix = snapshot.compactText();
2335
            if (!prefix.isEmpty()) {
2336
                int textX = startX + ICON_SIZE + 6;
2337
                int textY = y + 4;
2338
                textRenderer.render(prefix + " ", textX, textY,
2339
                        new RenderColor(foregroundColor(snapshot.cooling() ? timeColor : OPP_TIME_COLOR_GRACE)), false);
2340
            }
2341
2342
            y += EFFECT_LINE_HEIGHT;
2343
        }
2344
    }
2345
2346
    private Vec3 obtainEntityLerpedPos(Entity e, float tickDelta) {
2347
        try {
2348
            return e.getPosition(tickDelta);
2349
        } catch (NoSuchMethodError ex) {
2350
            if (e instanceof IEntity access) {
2351
                return access.get$InstantRenderPos().lerp(e.position(), tickDelta);
2352
            }
2353
            return e.position();
2354
        }
2355
    }
2356
2357
    private ScreenRect projectBoxScreen(AABB box, float tickDelta) {
2358
        double minX = Double.POSITIVE_INFINITY, minY = Double.POSITIVE_INFINITY;
2359
        double maxX = Double.NEGATIVE_INFINITY, maxY = Double.NEGATIVE_INFINITY;
2360
        boolean any = false;
2361
        double[] xs = {box.minX, box.maxX};
2362
        double[] ys = {box.minY, box.maxY};
2363
        double[] zs = {box.minZ, box.maxZ};
2364
        for (double x : xs) {
2365
            for (double y : ys) {
2366
                for (double z : zs) {
2367
                    Vec3 screen = ScreenProjection.worldToScreen(new Vec3(x, y, z), tickDelta);
2368
                    if (screen == null) continue;
2369
                    any = true;
2370
                    minX = Math.min(minX, screen.x);
2371
                    minY = Math.min(minY, screen.y);
2372
                    maxX = Math.max(maxX, screen.x);
2373
                    maxY = Math.max(maxY, screen.y);
2374
                }
2375
            }
2376
        }
2377
        if (!any || maxX <= minX || maxY <= minY) return null;
2378
        minX = Math.floor(minX);
2379
        minY = Math.floor(minY);
2380
        maxX = Math.ceil(maxX);
2381
        maxY = Math.ceil(maxY);
2382
        return new ScreenRect(minX, minY, maxX, maxY);
2383
    }
2384
2385
    private ItemStack[] getEquipmentSlots(Player player) {
2386
        ItemStack off = player.getOffhandItem();
2387
        ItemStack boots = player.getItemBySlot(EquipmentSlot.FEET);
2388
        ItemStack legs = player.getItemBySlot(EquipmentSlot.LEGS);
2389
        ItemStack chest = player.getItemBySlot(EquipmentSlot.CHEST);
2390
        ItemStack head = player.getItemBySlot(EquipmentSlot.HEAD);
2391
        return new ItemStack[]{boots, legs, chest, head, off};
2392
    }
2393
2394
    private List<List<EnchantLine>> buildEnchantLines(ItemStack[] slots) {
2395
        List<List<EnchantLine>> result = new ArrayList<>(slots.length);
2396
        for (ItemStack stack : slots) {
2397
            if (stack.isEmpty()) {
2398
                result.add(List.of());
2399
                continue;
2400
            }
2401
            List<EnchantLine> lines = formatEnchantments(stack);
2402
            result.add(lines.isEmpty() ? List.of() : lines);
2403
        }
2404
        return result;
2405
    }
2406
2407
    private int maxEnchantLines(List<List<EnchantLine>> lines) {
2408
        int max = 0;
2409
        for (List<EnchantLine> entry : lines) {
2410
            int size = entry.size();
2411
            if (size > max) max = size;
2412
        }
2413
        return max;
2414
    }
2415
2416
    private enum PresentationMode implements EnumValue.IdProvider {
2417
        TWO_D("2d"),
2418
        THREE_D("3d"),
2419
        HYBRID("hybrid");
2420
2421
        private final String id;
2422
2423
        PresentationMode(String id) {
2424
            this.id = id;
2425
        }
2426
2427
        @Override
2428
        public String id() {
2429
            return id;
2430
        }
2431
    }
2432
2433
    private static final class EffectCache {
2434
        int lastTick = -1;
2435
        List<MobEffectInstance> effects = List.of();
2436
    }
2437
2438
    private static final class EnchantCache {
2439
        int lastTick = -1;
2440
        int signature = 0;
2441
        List<List<EnchantLine>> lines = List.of();
2442
        int maxLines = 0;
2443
    }
2444
2445
    private record ScreenRect(double minX, double minY, double maxX, double maxY) {
2446
    }
2447
2448
    private record NameplateLayout(int nameX, int nameY, int width, int height, float labelScale,
2449
                                   String pingText, String distText, float bgX, float bgY, float bgW, float bgH,
2450
                                   int pingWidth, int pingGap, int nameWidth, int hpWidth, int hpGap,
2451
                                   boolean renderHead, float headX, float headY, float headSize,
2452
                                   float dividerX, float dividerY, float dividerW, float dividerH,
2453
                                   boolean renderTotemBadge, float totemDividerX, float totemDividerY,
2454
                                   float totemDividerW, float totemDividerH, float totemBadgeX, float totemBadgeY,
2455
                                   float totemBadgeW, float totemBadgeH, float totemIconSize) {
2456
    }
2457
2458
    private record EnchantLine(String text, int color) {
2459
    }
2460
2461
    private record EquipmentLayout(double[] centers, double rowWidth) {
2462
        private static EquipmentLayout empty() {
2463
            return new EquipmentLayout(new double[0], 0.0);
2464
        }
2465
    }
2466
2467
    private record WorldRenderEntry(Player player,
2468
                                    Vec3 anchor,
2469
                                    Vec3 bottomAnchor,
2470
                                    double distance,
2471
                                    double worldScale,
2472
                                    float alpha,
2473
                                    boolean renderNameplate,
2474
                                    boolean renderSlots,
2475
                                    boolean renderEffects,
2476
                                    ItemStack[] slots,
2477
                                    List<List<EnchantLine>> enchantLines,
2478
                                    int maxEnchantLines,
2479
                                    List<MobEffectInstance> effects,
2480
                                    int totemPopCount,
2481
                                    float totemPopAnimation,
2482
                                    ItemStack mainHand,
2483
                                    boolean renderMainHand,
2484
                                    ItemStack[] worldItems) {
2485
    }
2486
2487
    private record MainHandLayout(float x, float y, float width, float height,
2488
                                  float iconX, float iconY, float iconSize,
2489
                                  float textX, float textY, float textScale, Component text) {
2490
    }
2491
2492
    private record RenderEntry(Player player, double dist, int centerX, int nameY, int itemsY,
2493
                               boolean renderSlots, boolean renderNameplate,
2494
                               boolean renderEffects, LabelInfo labelInfo, int infoColor,
2495
                               NameplateLayout nameplateLayout, ItemStack mainHand, MainHandLayout mainHandLayout,
2496
                               ItemStack[] slots, List<List<EnchantLine>> enchantLines, int maxEnchantLines,
2497
                               List<MobEffectInstance> effects, int totemPopCount, float totemPopAnimation,
2498
                               float presentationAlpha) {
2499
    }
2500
2501
    private record LabelInfo(String pvpPrefix, Component styledName, String name, int ping, String pingText, String hp,
2502
                             int infoColor) {
2503
    }
2504
}
2505
KiwiClientRENDERsrc/main/java/com/tangykiwi/kiwiclient/module/render/Nametags.javaJava · 18 lines · 713 B

Enhanced nametags for entities.

SettingsPlayersAnimalsMobsItems
Nametags.javaJava · Minecraft 26.2 · 18 lines · 713 B · complete file, verbatimOriginal ↗
1
package com.tangykiwi.kiwiclient.module.render;
2
3
import com.tangykiwi.kiwiclient.module.Category;
4
import com.tangykiwi.kiwiclient.module.Module;
5
import com.tangykiwi.kiwiclient.module.setting.ToggleSetting;
6
7
public class Nametags extends Module {
8
    public Nametags() {
9
        super("Nametags", "Enhanced nametags for entities.", Category.RENDER,
10
            new ToggleSetting("Players", "Shows nametags over players", false),
11
            new ToggleSetting("Animals", "Shows nametags over animals", false),
12
            new ToggleSetting("Mobs", "Shows nametags over mobs", false),
13
            new ToggleSetting("Items", "Shows nametags over items", false));
14
    }
15
16
    // handling done in EntityRendererMixin
17
}
18
LiquidBounce (Kotlin)RENDERsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/render/nametags/ModuleNametags.ktKotlin · 123 lines · 4.5 KB

Improves the visibility of player's name tags and show additional information.

SettingsBorderWidthBackgroundRadius
ModuleNametags.ktKotlin · Minecraft 26.2 · 123 lines · 4.5 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.nametags
20
21
import net.ccbluex.fastutil.Pool
22
import net.ccbluex.liquidbounce.config.types.CurveValue.Axis.Companion.axis
23
import net.ccbluex.liquidbounce.event.events.OverlayRenderEvent
24
import net.ccbluex.liquidbounce.event.handler
25
import net.ccbluex.liquidbounce.features.module.ClientModule
26
import net.ccbluex.liquidbounce.features.module.ModuleCategories
27
import net.ccbluex.liquidbounce.render.FontManager
28
import net.ccbluex.liquidbounce.utils.combat.shouldBeShown
29
import net.ccbluex.liquidbounce.utils.entity.RenderedEntities
30
import net.ccbluex.liquidbounce.utils.entity.cameraDistance
31
import net.ccbluex.liquidbounce.utils.entity.cameraDistanceSq
32
import net.ccbluex.liquidbounce.utils.kotlin.EventPriorityConvention.FIRST_PRIORITY
33
import net.ccbluex.liquidbounce.utils.render.entity
34
import net.ccbluex.liquidbounce.utils.render.isCustom
35
import net.minecraft.client.gui.GuiGraphicsExtractor
36
import net.minecraft.client.renderer.entity.state.EntityRenderState
37
import org.joml.Vector2f
38
39
/**
40
 * Nametags module
41
 *
42
 * Makes player name tags more visible and adds useful information.
43
 */
44
object ModuleNametags : ClientModule("Nametags", ModuleCategories.RENDER) {
45
46
    init {
47
        tree(NametagTextFormatter)
48
        tree(NametagEquipment)
49
    }
50
51
    internal val borderWidth by float("BorderWidth", 1f, 0f..8f)
52
    internal val backgroundRadius by float("BackgroundRadius", 2f, 0f..16f)
53
    internal val scale = curve(
54
        "Scale",
55
        mutableListOf(Vector2f(0f, 1f), Vector2f(200f, 1f)),
56
        xAxis = "Distance" axis 0f..200f,
57
        yAxis = "Scale" axis 0.25f..4f,
58
    )
59
60
    val fontRenderer
61
        get() = FontManager.FONT_RENDERER
62
63
    private val nametagPool = Pool(::NametagRenderState, NametagRenderState::reset)
64
65
    private val nametagsToRender = mutableListOf<NametagRenderState>()
66
67
    override fun onDisabled() {
68
        RenderedEntities.unsubscribe(this)
69
        nametagPool.recycleAll(nametagsToRender)
70
        nametagsToRender.clear()
71
    }
72
73
    override fun onEnabled() {
74
        RenderedEntities.subscribe(this)
75
        RenderedEntities.onUpdated(::collectAndSortNametagsToRender)
76
    }
77
78
    @Suppress("unused")
79
    private val overlayRenderHandler = handler<OverlayRenderEvent>(priority = FIRST_PRIORITY) { event ->
80
        if (nametagsToRender.isEmpty()) {
81
            return@handler
82
        }
83
84
        event.context.drawNametags(event.tickDelta)
85
    }
86
87
    private fun GuiGraphicsExtractor.drawNametags(tickDelta: Float) {
88
        for (nametagInfo in nametagsToRender) {
89
            val (x, y) = nametagInfo.calculateScreenPos(tickDelta) ?: continue
90
91
            drawNametag(nametagInfo, x, y)
92
        }
93
    }
94
95
    /**
96
     * Collects all entities that should be rendered, gets the screen position, where the name tag should be displayed,
97
     * add what should be rendered ([NametagRenderState]). The nametags are sorted in order of rendering.
98
     */
99
    private fun collectAndSortNametagsToRender() {
100
        nametagPool.recycleAll(nametagsToRender)
101
        nametagsToRender.clear()
102
        for (entity in RenderedEntities) {
103
            val distance = entity.position().cameraDistance().toFloat()
104
            val scale = scale.transform(distance)
105
            if (scale > 0.01f) {
106
                val nametag = nametagPool.borrow()
107
                nametag.update(entity, scale)
108
                nametagsToRender += nametag
109
            }
110
        }
111
        nametagsToRender.sortWith(NAMETAG_COMPARATOR)
112
    }
113
114
    private val NAMETAG_COMPARATOR: Comparator<NametagRenderState> = Comparator.comparingDouble { nametag ->
115
        nametag.entity?.position()?.cameraDistanceSq() ?: Double.POSITIVE_INFINITY
116
    }
117
118
    fun shouldRenderVanillaNametag(state: EntityRenderState): Boolean {
119
        return !running || !(state.entity ?: return true).shouldBeShown() || state.isCustom
120
    }
121
122
}
123