feat: rewrite buff tooltip rendering to use chat tags

This commit is contained in:
Stephen T committed 2025-08-06 19:50:42 -05:00
1 parent 73d9ef79e1
commit 7d27973013
13 files changed
+219 -167

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ReLogic.Graphics;
using Terraria;
using Terraria.GameContent;
using Terraria.ID;
using Terraria.ModLoader;
using Terraria.UI.Chat;
namespace CalamityMod.ChatTags
{
public sealed class CalamityBuffTagHandler : AbstractTagHandler<CalamityBuffTagHandler>
{
public sealed class Snippet(int buffId) : TextSnippet
{
private const float IconSize = 26f;
public int BuffId => buffId;
// TODO: Include check for config option when it gets added.
public bool DrawIcon => true;
public override bool UniqueDraw(bool justCheckingString, out Vector2 size, SpriteBatch spriteBatch, Vector2 position = new Vector2(), Color color = new Color(), float scale = 1)
{
size = new Vector2(GetStringLength(FontAssets.MouseText.Value), IconSize);
if (!justCheckingString && (color.R != 0 || color.G != 0 || color.B != 0))
{
// Avoid re-drawing the icon when drawing borders.
if (DrawIcon)
{
// Tomat: I would love to support
// BuffLoader.[Pre/Post]Draw here, but it's not vaible
// because:
// 1. Main.DrawBuffIcon relies on LocalPlayer's buffs,
// 2. we can't control the source or destination
// rectangles.
if (Main.netMode != NetmodeID.Server && !Main.dedServ)
{
var texture = TextureAssets.Buff[BuffId];
spriteBatch.Draw(texture.Value, new Rectangle((int)position.X, (int)position.Y - 2, (int)IconSize, (int)IconSize), null, Color.White);
}
position.X += IconSize;
}
var buffColor = CalamityUtils.GetDebuffTooltipNameColor(buffId);
var name = $"{(DrawIcon ? " " : "")}{Lang.GetBuffName(buffId)}";
ChatManager.DrawColorCodedStringWithShadow(spriteBatch, FontAssets.MouseText.Value, name, position, buffColor, 0f, Vector2.Zero, new Vector2(scale));
}
return true;
}
public override float GetStringLength(DynamicSpriteFont font)
{
float iconSize = !DrawIcon ? 0f : IconSize + font.MeasureString(" ").X;
float size = iconSize + font.MeasureString(Lang.GetBuffName(buffId)).X;
return size * Scale;
}
}
protected override string[] TagNames { get; } = ["cbuff"];
public override TextSnippet Parse(string text, Color baseColor = new(), string options = null)
{
if (int.TryParse(text, out int buffId) && buffId >= 0 && buffId < BuffLoader.BuffCount)
{
return new Snippet(buffId);
}
if (BuffID.Search.TryGetId(text, out buffId))
{
return new Snippet(buffId);
}
return new TextSnippet(text);
}
}
}
+38
View File
@@ -0,0 +1,38 @@
using Microsoft.Xna.Framework;
using Terraria.ModLoader;
using Terraria.UI.Chat;
namespace CalamityMod.ChatTags
{
// Tomat: Adapted from NIGHTSHADE (ILoadableTagHandler<TSelf>), but I'm
// granting us this to use here.
/// <summary>
/// Abstracted implementation of <see cref="ITagHandler"/> with autoloading
/// capabilities for defining chat tags like modded content.
/// </summary>
/// <typeparam name="TSelf">The chat tag for loading.</typeparam>
public abstract class AbstractTagHandler<TSelf> : ITagHandler, ILoadable
where TSelf : AbstractTagHandler<TSelf>, new()
{
/// <summary>
/// Aliases for the tag.
/// </summary>
protected abstract string[] TagNames { get; }
/// <inheritdoc cref="ITagHandler.Parse"/>
public abstract TextSnippet Parse(string text, Color baseColor = new(), string options = null);
public virtual void Load(Mod mod)
{
ChatManager.Register<TSelf>(TagNames);
}
public virtual void Unload()
{
// No need to un-register the tag. ChatManager gets reinitialized
// by tML in response to modders having adding tags previously,
// anyway.
}
}
}
+29 -85
View File
@@ -6,6 +6,7 @@ using CalamityMod.Balancing;
using CalamityMod.Buffs.DamageOverTime;
using CalamityMod.Buffs.StatBuffs;
using CalamityMod.Buffs.StatDebuffs;
using CalamityMod.ChatTags;
using CalamityMod.CustomRecipes;
using CalamityMod.DataStructures;
using CalamityMod.Items.Accessories;
@@ -288,111 +289,54 @@ namespace CalamityMod.Items
tooltips.Insert(++difficultyTooltipIndex, donorLine);
}
var buffIdsInTooltip = new HashSet<int>();
//Last step in modifying tooltips: Finding and replacing instances of all the tooltips that should have them with item icons
//The debuffs in the tooltip that have been replaced. Used to display the ALT text
List<int> replacedDebuffs = new();
//the built in find and replace seems to just not work properly for this at times. This function does
void FindAndReplaceDebuff(List<TooltipLine> tooltips, string key, int debuffID)
foreach (var tooltip in tooltips)
{
var replacevalue = CalamityUtils.EmbedDebuff(debuffID);
bool replaced = false;
foreach (var tooltip in tooltips)
// Parse the tags of each line of text to find our buff tags'
// snippets (since they store the buff IDs).
var snippets = ChatManager.ParseMessage(tooltip.Text, Color.White);
foreach (var snippet in snippets)
{
if (tooltip.Text.Contains(key))
if (snippet is CalamityBuffTagHandler.Snippet buffSnippet)
{
replaced = true;
tooltip.Text = tooltip.Text.Replace(key, replacevalue);
buffIdsInTooltip.Add(buffSnippet.BuffId);
}
}
if (replaced)
{
replacedDebuffs.Add(debuffID);
}
}
Dictionary<string, int> debuffKeys = new() {
{"[Astral Infection]", ModContent.BuffType<AstralInfectionDebuff>()},
{"[Auric Rebuke]", ModContent.BuffType<AuricRebuke>()},
{"[Banishing Fire]", ModContent.BuffType<BanishingFire>()},
{"[Brimstone Flames]", ModContent.BuffType<BrimstoneFlames>()},
{"[Burning Blood]", ModContent.BuffType<BurningBlood>()},
{"[Brain Rot]", ModContent.BuffType<BrainRot>()},
{"[Demonic Flames]", ModContent.BuffType<DemonicFlames>()},
{"[Elemental Mix]", ModContent.BuffType<ElementalMix>()},
{"[Crush Depth]", ModContent.BuffType<CrushDepth>()},
{"[Riptide]", ModContent.BuffType<RiptideDebuff>()},
{"[Dragonfire]", ModContent.BuffType<Dragonfire>()},
{"[God Slayer Inferno]", ModContent.BuffType<GodSlayerInferno>()},
{"[Heavy Bleeding]", ModContent.BuffType<HeavyBleeding>()},
{"[Holy Flames]", ModContent.BuffType<HolyFlames>()},
{"[Laceration]", ModContent.BuffType<Laceration>()},
{"[Mana Burn]", ModContent.BuffType<ManaBurn>()},
{"[Miracle Blight]", ModContent.BuffType<MiracleBlight>()},
{"[Nightwither]", ModContent.BuffType<Nightwither>()},
{"[Plague]", ModContent.BuffType<Plague>()},
{"[Sage Poison]", ModContent.BuffType<SagePoison>()},
{"[Shred]", ModContent.BuffType<Shred>()},
{"[Static Discharge]", ModContent.BuffType<StaticDischarge>()},
{"[Sulphuric Poisoning]", ModContent.BuffType<SulphuricPoisoning>()},
{"[True Vulnerability Hex]", ModContent.BuffType<TrueVulnerabilityHex>()},
{"[Vaporified]", ModContent.BuffType<Vaporfied>()},
{"[Vermillion Flux]", ModContent.BuffType<VermillionFlux>()},
{"[Voidfrost]", ModContent.BuffType<Voidfrost>()},
{"[Vulnerability Hex]", ModContent.BuffType<VulnerabilityHex>()},
{"[Regeneraga]", ModContent.BuffType<AbsorberRegen>()},
{"[Cosmic Freeze]", ModContent.BuffType<CosmicFreeze>()},
{"[Mushy]", ModContent.BuffType<Mushy>()},
{"[Reaver Rage]", ModContent.BuffType<ReaverRage>()},
{"[Absorber Affliction]", ModContent.BuffType<AbsorberAffliction>()},
{"[Armor Crunch]", ModContent.BuffType<ArmorCrunch>()},
{"[Crumbling]", ModContent.BuffType<Crumbling>()},
{"[Eutrophication]", ModContent.BuffType<Eutrophication>()},
{"[Galvanic Corrosion]", ModContent.BuffType<GalvanicCorrosion>()},
{"[Glacial State]", ModContent.BuffType<GlacialState>()},
{"[Hadopelagic Pressure]", ModContent.BuffType<HadopelagicPressure>()},
{"[Irradiated]", ModContent.BuffType<Irradiated>()},
{"[Marked for Death]", ModContent.BuffType<MarkedforDeath>()},
{"[Temporal Sadness]", ModContent.BuffType<TemporalSadness>()},
{"[Time Distortion]", ModContent.BuffType<TimeDistortion>()},
{"[Whispering Death]", ModContent.BuffType<WhisperingDeath>()},
{"[Daybroken]", ModContent.BuffType<Daybroken>()},
{"[Shadowflame]", ModContent.BuffType<Shadowflame>()},
{"[Potion Sickness]", BuffID.PotionSickness},
{"[Acid Venom]", BuffID.Venom},
{"[Betsy's Curse]", BuffID.BetsysCurse},
{"[Cursed Inferno]", BuffID.CursedInferno},
{"[Frostbite]", BuffID.Frostburn2},
{"[Frostburn]", BuffID.Frostburn},
{"[On Fire!]", BuffID.OnFire},
{"[Hellfire]", BuffID.OnFire3},
{"[Ichor]", BuffID.Ichor},
{"[Oiled]", BuffID.Oiled},
{"[Poisoned]", BuffID.Poisoned},
{"[Slimed]", BuffID.Slimed},
{"[Wet]", BuffID.Wet},
{"[Electrified]", BuffID.Electrified}
};
foreach (var debuff in debuffKeys)
{
FindAndReplaceDebuff(tooltips, debuff.Key, debuff.Value);
}
if (replacedDebuffs.Count > 0)
if (buffIdsInTooltip.Count > 0)
{
bool showTheTip = false;
bool foundDebuff = false;
for (var i = 0; i < replacedDebuffs.Count; i++)
foreach (int buffId in buffIdsInTooltip)
{
if (CalamityUtils.GetTextValue("Buffs." + BuffID.Search.GetName(replacedDebuffs[i]) + ".ItemTooltip") == "")
string tooltipKey = "";
if (buffId < BuffID.Count)
{
tooltipKey = $"Mods.Terraria.Buffs.{BuffID.Search.GetName(buffId)}.ItemTooltip";
}
else
{
var modBuff = BuffLoader.GetBuff(buffId);
tooltipKey = $"Mods.{modBuff.Mod.Name}.Buffs.{modBuff.Name}.ItemTooltip";
}
if (!Language.Exists(tooltipKey))
{
continue;
}
foundDebuff = true;
if (!PlayerInput.Triggers.Current.SmartCursor)
{
showTheTip = true;
break;
}
tooltips.Insert(++lastTooltipIndex, new TooltipLine(Mod, "CalamityMod:AltExpandTooltip" + i, $"{CalamityUtils.EmbedDebuff(replacedDebuffs[i])}\n{CalamityUtils.GetTextValue("Buffs." + BuffID.Search.GetName(replacedDebuffs[i]).Replace("CalamityMod/", "") + ".ItemTooltip")}"));
tooltips.Insert(++lastTooltipIndex, new TooltipLine(Mod, "CalamityMod:AltExpandTooltip" + buffId, $"[cbuff:{buffId}]\n{Language.GetTextValue(tooltipKey)}"));
}
if (showTheTip)
{
var str = PlayerInput.CurrentProfile.InputModes[InputMode.Keyboard].KeyStatus["SmartCursor"].First().ToString();
@@ -1661,22 +1661,3 @@ Shadowflame: {
DisplayName: Shadowflame
ItemTooltip: Heat - 30 DPS
}
Venom.ItemTooltip: Sickness - 30 DPS
BetsysCurse.ItemTooltip: -40 defense
CursedInferno.ItemTooltip: Heat - 24 DPS
Frostburn2.ItemTooltip: Cold - 50 DPS
Frostburn.ItemTooltip: Cold - 8 DPS
OnFire3.ItemTooltip: Heat - 15 DPS
OnFire.ItemTooltip: Heat - 6 DPS
Ichor.ItemTooltip: -10 defense
Oiled.ItemTooltip:
'''
Heat - 25 DPS. Recieves 2x the effect from Heat multipliers
Only does damage when paired with another Heat debuff
'''
Poisoned.ItemTooltip: Sickness - 6 DPS
PotionSickness.ItemTooltip: ""
Slimed.ItemTooltip: Enhances Heat debuff damage
Wet.ItemTooltip: Enhances Electric debuff damage
Electrified.ItemTooltip: Electric - 10.5 DPS. Deals 4x damage to moving targets
@@ -248,7 +248,7 @@ BloodflareHeadRogue: {
Being over 80% life boosts your defense by 30 and rogue crit by 5%
Being below 80% life boosts your rogue damage by 10%
Rogue critical strikes burst into blood orbs
Picking up these blood orbs reduces the duration of [cbuff:Terraria/PotionSickness]
Picking up these blood orbs reduces the duration of [cbuff:PotionSickness]
'''
}
@@ -734,7 +734,7 @@ SanguineFlare: {
'''
Charges up a sanguine flare that gains power over time
When striking an enemy, this flare causes a bloodsplosion and splits into blood orbs
Picking up these blood orbs reduces the duration of [cbuff:Terraria/PotionSickness]
Picking up these blood orbs reduces the duration of [cbuff:PotionSickness]
'''
}
@@ -991,7 +991,7 @@ Viscera: {
'''
Fires a rapid barrage of piercing blood beams
The first enemy struck by each beam will burst into blood orbs
Picking up these blood orbs reduces the duration of [cbuff:Terraria/PotionSickness]
Picking up these blood orbs reduces the duration of [cbuff:PotionSickness]
Each successive beam in the barrage deals more damage
The last beam of the barrage instead explodes upon hitting an enemy
'''
@@ -777,7 +777,7 @@ Lacerator: {
Striking enemies conjures a bloody saw to shred them
The saw does more damage the more often the yoyo hits, and fades away when not striking enemies
Enemies touching the edge of the sawblade get blood orbs torn out of them
Picking up these blood orbs reduces the duration of [cbuff:Terraria/PotionSickness]
Picking up these blood orbs reduces the duration of [cbuff:PotionSickness]
The direction of the saw's spin depends on which direction you originally threw the yoyo
[GFB]
'''
@@ -1350,7 +1350,7 @@ TheMutilator: {
'''
Striking enemies empowers The Mutilator, increasing its damage
At full charge, striking enemies causes a blood orb explosion
Picking up these blood orbs reduces the duration of [cbuff:Terraria/PotionSickness]
Picking up these blood orbs reduces the duration of [cbuff:PotionSickness]
'''
}
@@ -115,7 +115,7 @@ ArterialAssault: {
'''
Fires a group of 5 homing blood arrows
These blood arrows burst into blood orbs upon striking an enemy
Picking up these blood orbs reduces the duration of [cbuff:Terraria/PotionSickness]
Picking up these blood orbs reduces the duration of [cbuff:PotionSickness]
'''
}
@@ -198,7 +198,7 @@ BloodBoiler: {
Tooltip:
'''
Fires twin streams of bloodfire that returns to you
Retuning bloodfire reduces [cbuff:Terraria/PotionSickness] if it struck an enemy
Retuning bloodfire reduces [cbuff:PotionSickness] if it struck an enemy
Uses your health as ammo
20% chance to save health
'''
@@ -77,7 +77,7 @@ BloodsoakedCrasher: {
Throws a bloody axe that is affected by gravity and can bounce twice
The axe speeds up over time, but will slow down upon hitting an enemy
Spews blood orbs upon enemy hits
Picking up these blood orbs reduces the duration of [cbuff:Terraria/PotionSickness]
Picking up these blood orbs reduces the duration of [cbuff:PotionSickness]
Stealth strikes spawn homing blood bolts on hit
'''
}
@@ -293,7 +293,7 @@ DragonbloodDisgorger: {
'''
Summons a skeletal dragon and her two children
Baby spits burst into blood orbs upon hitting an enemy
Picking up these blood orbs reduces the duration of [cbuff:Terraria/PotionSickness]
Picking up these blood orbs reduces the duration of [cbuff:PotionSickness]
Requires 6 minion slots to be summoned
There can only be one family at a time
'''
@@ -14,8 +14,8 @@ ClaretCannon: {
Fires a hypercondensed claret round
The round explodes upon striking an enemy and releases blood orbs
The explosion shreds enemies, inflicting [cbuff:CalamityMod/Laceration] and dramatically reducing their defense
Picking up the blood orbs will reduce [cbuff:Terraria/PotionSickness] when possible
If you do not have [cbuff:Terraria/PotionSickness], your natural regeneration will be enhanced
Picking up the blood orbs will reduce [cbuff:PotionSickness] when possible
If you do not have [cbuff:PotionSickness], your natural regeneration will be enhanced
Can only fire once every 10 seconds
'''
}
@@ -0,0 +1,18 @@
Venom.ItemTooltip: Sickness - 30 DPS
BetsysCurse.ItemTooltip: -40 defense
CursedInferno.ItemTooltip: Heat - 24 DPS
Frostburn2.ItemTooltip: Cold - 50 DPS
Frostburn.ItemTooltip: Cold - 8 DPS
OnFire3.ItemTooltip: Heat - 15 DPS
OnFire.ItemTooltip: Heat - 6 DPS
Ichor.ItemTooltip: -10 defense
Oiled.ItemTooltip:
'''
Heat - 25 DPS. Recieves 2x the effect from Heat multipliers
Only does damage when paired with another Heat debuff
'''
Poisoned.ItemTooltip: Sickness - 6 DPS
PotionSickness.ItemTooltip: "AAA"
Slimed.ItemTooltip: Enhances Heat debuff damage
Wet.ItemTooltip: Enhances Electric debuff damage
Electrified.ItemTooltip: Electric - 10.5 DPS. Deals 4x damage to moving targets
+41 -52
View File
@@ -290,17 +290,6 @@ namespace CalamityMod
tooltips.FindAndReplace("[KEY]", finalKey);
}
/// <summary>
/// Embeds and item icon and it's name
/// set the justItemIcon bool to true to get just the icon without the item name
/// </summary>
/// <param name="itemType"></param>
/// <param name="justItemIcon"></param>
/// <returns></returns>
public static string EmbedItem(int itemType, bool justItemIcon = false)
{
return justItemIcon ? $"[i:{itemType}]" : $"[i:{itemType}] {ContentSamples.ItemsByType[itemType].Name}";
}
public static Color FireDebuffColor => new(253, 107, 2);
public static Color SicknessDebuffColor => new(136, 198, 10);
public static Color WaterDebuffColor => new(105, 147, 255);
@@ -310,61 +299,61 @@ namespace CalamityMod
public static Color TypelessDebuffColor => new(230, 202, 250);
public static Color VulnHexDebuffColor => new(196, 35, 43);
public static Color MiracleBlightDebuffColor => Main.DiscoColor;
public static string EmbedDebuff(int debuff)
private static readonly Dictionary<int, List<(Color, float)>> debuffColorWeightsCache = [];
public static Color GetDebuffTooltipNameColor(int debuffId)
{
Color color = TypelessDebuffColor;
List<(Color, float)> debuffColorWeights = new();
if (debuff == ModContent.BuffType<VulnerabilityHex>() || debuff == ModContent.BuffType<TrueVulnerabilityHex>())
var color = TypelessDebuffColor;
if (debuffId == ModContent.BuffType<VulnerabilityHex>() || debuffId == ModContent.BuffType<TrueVulnerabilityHex>())
{
color = Color.Lerp(VulnHexDebuffColor, FireDebuffColor, (MathF.Sin(Main.GlobalTimeWrappedHourly * 2) + 1) / 4f);
}
else if (debuff == ModContent.BuffType<MiracleBlight>())
else if (debuffId == ModContent.BuffType<MiracleBlight>())
{
color = MiracleBlightDebuffColor;
}
else
else if (BuffDatasets.DebuffDataset[debuffId] is not null)
{
if (BuffDatasets.DebuffDataset[debuff] is not null)
if (!debuffColorWeightsCache.TryGetValue(debuffId, out var weights))
{
debuffColorWeights.Add((SicknessDebuffColor, BuffDatasets.DebuffDataset[debuff].SicknessDebuffScaling));
debuffColorWeights.Add((FireDebuffColor, BuffDatasets.DebuffDataset[debuff].HeatDebuffScaling));
debuffColorWeights.Add((WaterDebuffColor, BuffDatasets.DebuffDataset[debuff].WaterDebuffScaling));
debuffColorWeights.Add((ElectricDebuffColor, BuffDatasets.DebuffDataset[debuff].ElectricDebuffScaling));
debuffColorWeights.Add((ColdDebuffColor, BuffDatasets.DebuffDataset[debuff].ColdDebuffScaling));
weights =
[
(SicknessDebuffColor, BuffDatasets.DebuffDataset[debuffId].SicknessDebuffScaling),
(FireDebuffColor, BuffDatasets.DebuffDataset[debuffId].HeatDebuffScaling),
(WaterDebuffColor, BuffDatasets.DebuffDataset[debuffId].WaterDebuffScaling),
(ElectricDebuffColor, BuffDatasets.DebuffDataset[debuffId].ElectricDebuffScaling),
(ColdDebuffColor, BuffDatasets.DebuffDataset[debuffId].ColdDebuffScaling),
];
}
float totalWeight = 0;
Vector4 colordata = new();
foreach (var item in debuffColorWeights)
{
totalWeight += item.Item2;
colordata += item.Item1.ToVector4() * item.Item2;
}
if (totalWeight < 1)
{
colordata += TypelessDebuffColor.ToVector4() * (1 - totalWeight);
totalWeight += (1 - totalWeight);
}
if (totalWeight != 0)
{
colordata /= totalWeight;
color = new Color(colordata);
}
float totalWeight = 0;
Vector4 normalColor = new();
foreach (var item in weights)
{
totalWeight += item.Item2;
// ReSharper disable once PossiblyImpureMethodCallOnReadonlyVariable
normalColor += item.Item1.ToVector4() * item.Item2;
}
if (totalWeight < 1)
{
normalColor += TypelessDebuffColor.ToVector4() * (1 - totalWeight);
totalWeight += (1 - totalWeight);
}
if (totalWeight != 0)
{
normalColor /= totalWeight;
color = new Color(normalColor);
}
}
var colorText = $"[c/{ColorToHex(color)}:";
var outText = EmbedItem(CalamityMod.Instance.Find<ModItem>(BuffID.Search.GetName(debuff).Replace("CalamityMod/", "") + "IconItem").Type);
if (true) //This is for when configs are updated to be able to disable item icons in tooltips
{
outText = outText.Replace("]", "]" + colorText) + "]";
}
else
{
outText = colorText + outText + "]";
}
return outText;
return color;
}
/// <summary>
/// Converts a Color into a Hex string usable for tooltip/text coloring.
/// </summary>