From 6152e817083101a126edae2467605ec68beec1e7 Mon Sep 17 00:00:00 2001 From: Listentowind <2926669682@qq.com> Date: Sun, 28 Dec 2025 15:01:35 +0800 Subject: [PATCH 01/53] proj loc file clean and fix --- .../en-US/Mods.CalamityMod.Projectiles.Magic.hjson | 6 +++--- .../en-US/Mods.CalamityMod.Projectiles.Melee.hjson | 1 + .../en-US/Mods.CalamityMod.Projectiles.Ranged.hjson | 2 +- .../en-US/Mods.CalamityMod.Projectiles.Rogue.hjson | 9 ++++----- Projectiles/Melee/ScorpiusConstellation.cs | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Localization/en-US/Mods.CalamityMod.Projectiles.Magic.hjson b/Localization/en-US/Mods.CalamityMod.Projectiles.Magic.hjson index a4253a7fe0..d0515c4a86 100644 --- a/Localization/en-US/Mods.CalamityMod.Projectiles.Magic.hjson +++ b/Localization/en-US/Mods.CalamityMod.Projectiles.Magic.hjson @@ -8,6 +8,7 @@ AerSigilBlast.DisplayName: Aer Blast AerSigilFeather.DisplayName: Aer Feather AerSigilMissile.DisplayName: Aer Missile AetherBeam.DisplayName: Aether Beam +AlphaDraconisStar.DisplayName: Shooting Star AnahitasArpeggioNote.DisplayName: Anahita's Song Ancient2.DisplayName: Ancient Dust ApoctosisBlast.DisplayName: Apoctosis Blast @@ -48,8 +49,6 @@ CauldronProjSmall.DisplayName: Smaullerdron ChronoIcicleLarge.DisplayName: Chrono Icicle ChronoIcicleSmall.DisplayName: Chrono Icicle ChronomancersScytheHoldout.DisplayName: Chronomancer's Scythe -AlphaDraconisStar.DisplayName: Shooting Star -DracoConstellation.DisplayName: Draco ClimaxBeam.DisplayName: Voltaic Bolt ClimaxProj.DisplayName: Voltaic Orb CoralSpike.DisplayName: Coral Spike @@ -59,9 +58,9 @@ CosmicTentacle.DisplayName: Dark Tentacle CryoBlast.DisplayName: Cryo Blast DarkSparkBeam.DisplayName: Dark Spark Beam DarkSparkPrism.DisplayName: Dark Crystal -HyperdeathRiftScepterBeam.DisplayName: Hyperdeath Rift Ripper DeathValleyDusterProjectile.DisplayName: Death Valley Duster DeathhailBeam.DisplayName: Deathhail Beam +DracoConstellation.DisplayName: Draco EelDrop.DisplayName: Acid Eel Drop EidolicWailSoundwave.DisplayName: Eidolic Wail EldritchTentacle.DisplayName: Eldritch Tentacle @@ -101,6 +100,7 @@ HellfireExplosionFriendly.DisplayName: Explosion HellwingBat.DisplayName: Ashen Hellwing HolyFlame.DisplayName: Holy Flame HolyLaser.DisplayName: Holy Laser +HyperdeathRiftScepterBeam.DisplayName: Hyperdeath Rift Ripper IceBarrageMain.DisplayName: Ice Barrage IceBlock.DisplayName: Ice Barrage Block IceBlockIcicle.DisplayName: Ice Barrage Icicle diff --git a/Localization/en-US/Mods.CalamityMod.Projectiles.Melee.hjson b/Localization/en-US/Mods.CalamityMod.Projectiles.Melee.hjson index 341d5df47d..b77f498176 100644 --- a/Localization/en-US/Mods.CalamityMod.Projectiles.Melee.hjson +++ b/Localization/en-US/Mods.CalamityMod.Projectiles.Melee.hjson @@ -227,6 +227,7 @@ SanguineFury.DisplayName: Sanguine Fury SanguineFuryDash.DisplayName: Shredding Lunge SanguineFuryWheel.DisplayName: Sanguine Bladewheel ScorcherExplosion.DisplayName: Scorching Crystal Blast +ScorpiusConstellation.DisplayName: Scorpius Constellation ScourgeoftheCosmosMini.DisplayName: Miniature Cosmic Scourge ScourgeoftheCosmosProj.DisplayName: Cosmic Scourge SeekingScorcherProj.DisplayName: Scorching Seeker diff --git a/Localization/en-US/Mods.CalamityMod.Projectiles.Ranged.hjson b/Localization/en-US/Mods.CalamityMod.Projectiles.Ranged.hjson index 10e81d3a57..72c9edbf3f 100644 --- a/Localization/en-US/Mods.CalamityMod.Projectiles.Ranged.hjson +++ b/Localization/en-US/Mods.CalamityMod.Projectiles.Ranged.hjson @@ -97,6 +97,7 @@ FungiOrb2.DisplayName: Fungi Orb GemTechGreenFlechette.DisplayName: Gem Tech Flechette GodSlayerSlugProj.DisplayName: God Slayer Slug HalleysComet.DisplayName: Halley's Comet +HalleysStarburst.DisplayName: Halley's Starburst HandheldTankShell.DisplayName: Tank Shell HeavenlyGaleProj.DisplayName: Heavenly Gale HellbornProj.DisplayName: Hell-born Gunblast @@ -266,4 +267,3 @@ WaterSpout.DisplayName: Spout WildfireBloomFire.DisplayName: Wildfire Fire WildfireBloomFlare.DisplayName: Wildfire Flare WulfrumScrapBullet.DisplayName: High Speed Scrap -HalleysStarburst.DisplayName: Halleys Starburst diff --git a/Localization/en-US/Mods.CalamityMod.Projectiles.Rogue.hjson b/Localization/en-US/Mods.CalamityMod.Projectiles.Rogue.hjson index fdc43eba28..d14ff208af 100644 --- a/Localization/en-US/Mods.CalamityMod.Projectiles.Rogue.hjson +++ b/Localization/en-US/Mods.CalamityMod.Projectiles.Rogue.hjson @@ -165,6 +165,7 @@ LostSoulFriendly.DisplayName: Lost Soul LuminousShard.DisplayName: Stardust Shard LunarKunaiProj.DisplayName: Lunar Kunai LuxorsGiftRogue.DisplayName: Luxor's Rogue +LyraConstellation.DisplayName: Lyra Constellation MalachiteBolt.DisplayName: Malachite MalachiteProj.DisplayName: Malachite MalachiteStealth.DisplayName: Malachite @@ -183,9 +184,6 @@ NanoblackSplit.DisplayName: Nanoblack Blade NanoblackStealthSplit.DisplayName: Nanoblack Afterimage NastyChollaBol.DisplayName: Nasty Cholla NastyChollaNeedle.DisplayName: Cactus Needle -VegaProjectile.DisplayName: Vega -VegaSpark.DisplayName: Vega Spark -VegaStar.DisplayName: Vega Star OrichalcumSpikedGemstoneProjectile.DisplayName: Orichalcum Gemstone PalladiumJavelinProjectile.DisplayName: Palladium Javelin PartisanExplosion.DisplayName: Profaned Explosion @@ -315,6 +313,9 @@ ValariBoomerang.DisplayName: Frostcrush Valari Valaricicle.DisplayName: Valaricicle Valaricicle2.DisplayName: Valaricicle ValedictionBoomerang.DisplayName: Valediction +VegaProjectile.DisplayName: Vega +VegaSpark.DisplayName: Vega Spark +VegaStar.DisplayName: Vega Star VeneratedKnife.DisplayName: Venerated Knife WaveSkipperProjectile.DisplayName: Wave Skipper WebBallBol.DisplayName: Web Ball @@ -325,5 +326,3 @@ WrathwingCinder.DisplayName: Wrathwing Eruption WrathwingFireball.DisplayName: Wrathwing Fireball WrathwingSpear.DisplayName: Wrathwing WulfrumKnifeProj.DisplayName: Wulfrum Knife -LyraConstellation.DisplayName: Lyra Constellation -ScorpiusConstellation.DisplayName: Scorpius Constellation diff --git a/Projectiles/Melee/ScorpiusConstellation.cs b/Projectiles/Melee/ScorpiusConstellation.cs index e79122c6fa..b7bc4ae366 100644 --- a/Projectiles/Melee/ScorpiusConstellation.cs +++ b/Projectiles/Melee/ScorpiusConstellation.cs @@ -14,7 +14,7 @@ namespace CalamityMod.Projectiles.Melee { public class ScorpiusConstellation : ModProjectile, ILocalizedModType { - public new string LocalizationCategory => "Projectiles.Rogue"; + public new string LocalizationCategory => "Projectiles.Melee"; public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; public static int lifetime = 150; From 3c47cc5248b47df8473ae4730a017c6415f59546 Mon Sep 17 00:00:00 2001 From: Done_22 Date: Sun, 28 Dec 2025 14:16:10 +0200 Subject: [PATCH 02/53] phalanx surge buff --- Items/Weapons/DraedonsArsenal/PhalanxSurge.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Items/Weapons/DraedonsArsenal/PhalanxSurge.cs b/Items/Weapons/DraedonsArsenal/PhalanxSurge.cs index 00ab2ba3b1..aae000f87b 100644 --- a/Items/Weapons/DraedonsArsenal/PhalanxSurge.cs +++ b/Items/Weapons/DraedonsArsenal/PhalanxSurge.cs @@ -28,7 +28,7 @@ namespace CalamityMod.Items.Weapons.DraedonsArsenal Item.width = 64; Item.height = 36; Item.DamageType = DamageClass.Ranged; - Item.damage = 150; + Item.damage = 175; Item.knockBack = 4f; Item.useTime = 30; Item.useAnimation = 30; From 84a50c2f5b9edd82fbd0a14ae5d1e57246be976b Mon Sep 17 00:00:00 2001 From: Flowaria Date: Sun, 21 Dec 2025 10:22:32 +0900 Subject: [PATCH 03/53] Add CountAs and IsBasedOn feature to DifficultyMode --- Systems/Mechanic/DifficultyModeSystem.cs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/Systems/Mechanic/DifficultyModeSystem.cs b/Systems/Mechanic/DifficultyModeSystem.cs index 87bdaaea6f..72ddc7fa36 100644 --- a/Systems/Mechanic/DifficultyModeSystem.cs +++ b/Systems/Mechanic/DifficultyModeSystem.cs @@ -59,7 +59,7 @@ namespace CalamityMod.Systems case GameModeID.Normal: { // vanilla game mode in classic, but cal difficulty >= expert - if (GetCurrentDifficulty == ModContent.GetInstance() || GetCurrentDifficulty == ModContent.GetInstance()) + if (GetCurrentDifficulty.CountAs() || GetCurrentDifficulty.CountAs()) { ModeIndicatorUI.SwitchToDifficulty(ModContent.GetInstance(), broadcast: true); } @@ -68,7 +68,7 @@ namespace CalamityMod.Systems case GameModeID.Expert: { // if death was activated, change it to revengence - if (GetCurrentDifficulty == ModContent.GetInstance()) + if (GetCurrentDifficulty.CountAs()) { ModeIndicatorUI.SwitchToDifficulty(ModContent.GetInstance(), broadcast: true); } @@ -77,7 +77,7 @@ namespace CalamityMod.Systems case GameModeID.Master: { // if revengence and master both activated, change it to death - if (GetCurrentDifficulty != ModContent.GetInstance() && CalamityWorld.revenge) + if (!GetCurrentDifficulty.CountAs() && CalamityWorld.revenge) { ModeIndicatorUI.SwitchToDifficulty(ModContent.GetInstance(), broadcast: true); } @@ -241,6 +241,7 @@ namespace CalamityMod.Systems // This is registered in DifficultyModeSystem.OnModLoad // Note that DifficultyModeSystem.Load can't ensure system is loaded after all modes } + public abstract bool Enabled { get; set; @@ -271,6 +272,16 @@ namespace CalamityMod.Systems public virtual bool RequiresDifficulty(DifficultyMode mode) => false; public virtual int[] FavoredDifficultyAtTier(int tier) => [0]; + + public virtual bool IsBasedOn(DifficultyMode mode) => false; + + public bool CountAs() where Difficulty : DifficultyMode => CountAs(ModContent.GetInstance()); + public bool CountAs(DifficultyMode mode) + { + if (mode == this) return true; + if (IsBasedOn(mode)) return true; + return false; + } } public class NoDifficulty : DifficultyMode From fb3fb7c038f5af98678d690bb335793720927a96 Mon Sep 17 00:00:00 2001 From: Doze-Zoze Date: Sat, 5 Apr 2025 01:05:23 -0500 Subject: [PATCH 04/53] Reworked Statis' (now Sentinel's) Blessing, OOA Accessories, Phantomic Artifact, and Hallowed Rune --- CalPlayer/CalamityPlayerLifeRegen.cs | 2 +- CalPlayer/CalamityPlayerOnHit.cs | 22 +++++++++++----------- Projectiles/Healing/PhantomicHeart.cs | 3 ++- Projectiles/Summon/HallowedStarSummon.cs | 2 ++ Projectiles/Summon/PhantomicDagger.cs | 16 +++++----------- 5 files changed, 21 insertions(+), 24 deletions(-) diff --git a/CalPlayer/CalamityPlayerLifeRegen.cs b/CalPlayer/CalamityPlayerLifeRegen.cs index e99cce9b3e..2bc5d07102 100644 --- a/CalPlayer/CalamityPlayerLifeRegen.cs +++ b/CalPlayer/CalamityPlayerLifeRegen.cs @@ -582,7 +582,7 @@ namespace CalamityMod.CalPlayer if (silvaSet) Player.lifeRegen += SilvaArmor.SetBonusRegenBoost; - if (phantomicHeartRegen <= 720 && phantomicHeartRegen >= 600) + if (phantomicHeartRegen > 0 && phantomicHeartRegen < 1000) { Player.lifeRegen += PhantomicArtifact.RegenBoost; if (Main.rand.NextBool()) diff --git a/CalPlayer/CalamityPlayerOnHit.cs b/CalPlayer/CalamityPlayerOnHit.cs index 508665485c..60fe2b408a 100644 --- a/CalPlayer/CalamityPlayerOnHit.cs +++ b/CalPlayer/CalamityPlayerOnHit.cs @@ -890,8 +890,6 @@ namespace CalamityMod.CalPlayer { var source = proj.GetSource_FromThis(); - if (npcCheck) - { if (phantomicArtifact) { int restoreBuff = BuffType(); @@ -903,10 +901,10 @@ namespace CalamityMod.CalPlayer empowerBuff, shieldBuff }); - Player.AddBuff(buffType, 60); + Player.AddBuff(buffType, 120); if (buffType == restoreBuff) { - if (phantomicHeartRegen == 1000 && Player.ownedProjectileCounts[ProjectileType()] == 0 && Main.rand.NextBool(20)) + if (phantomicHeartRegen == 1000 && Player.ownedProjectileCounts[ProjectileType()] == 0) { Vector2 target = proj.Center; target.Y += Main.rand.Next(-50, 50); @@ -916,10 +914,10 @@ namespace CalamityMod.CalPlayer } else if (buffType == empowerBuff) { - if (Player.ownedProjectileCounts[ProjectileType()] < 3 && Main.rand.NextBool(10)) + if (Player.ownedProjectileCounts[ProjectileType()] < 3 && Main.rand.NextBool(4)) { int damage = (int)Player.GetTotalDamage().ApplyTo(100); - Projectile.NewProjectile(source, proj.position, proj.velocity, ProjectileType(), damage, 1f, Player.whoAmI); + Projectile.NewProjectile(source, Player.Center, new Vector2(Player.velocity.X,Player.velocity.Y-10).RotatedByRandom(0.3f), ProjectileType(), damage, 1f, Player.whoAmI); } } else @@ -936,7 +934,7 @@ namespace CalamityMod.CalPlayer BuffType(), BuffType() }); - Player.AddBuff(buffType, 60); + Player.AddBuff(buffType, 120); } else if (sGlyph) { @@ -946,9 +944,8 @@ namespace CalamityMod.CalPlayer BuffType(), BuffType() }); - Player.AddBuff(buffType, 60); + Player.AddBuff(buffType, 120); } - } // Fearmonger set gains regen duration when any minion lands any hit if (fearmongerSet) @@ -1003,10 +1000,13 @@ namespace CalamityMod.CalPlayer if (hallowedRuneCooldown <= 0) { hallowedRuneCooldown = 180; - Vector2 spawnPosition = position - new Vector2(0f, 920f).RotatedByRandom(0.3f); + for (var i = 0; i < 3; i++) + { + Vector2 spawnPosition = position - new Vector2(0f, 920f).RotatedByRandom(0.3f); float speed = Main.rand.NextFloat(17f, 23f); int hallowedDamage = (int)Player.GetTotalDamage().ApplyTo(50); - Projectile.NewProjectile(source, spawnPosition, Vector2.Normalize(position - spawnPosition) * speed, ProjectileType(), hallowedDamage, 3f, proj.owner); + Projectile.NewProjectile(source, spawnPosition, Vector2.Normalize(position - spawnPosition) * speed, ProjectileType(), hallowedDamage, 3f, proj.owner); + } } } } diff --git a/Projectiles/Healing/PhantomicHeart.cs b/Projectiles/Healing/PhantomicHeart.cs index ea6c6c6de7..6a5c000682 100644 --- a/Projectiles/Healing/PhantomicHeart.cs +++ b/Projectiles/Healing/PhantomicHeart.cs @@ -25,6 +25,7 @@ namespace CalamityMod.Projectiles.Healing Projectile.width = 28; Projectile.height = 42; Projectile.friendly = true; + Projectile.tileCollide = false; Projectile.alpha = 20; Projectile.penetrate = -1; Projectile.timeLeft = 600; @@ -68,7 +69,7 @@ namespace CalamityMod.Projectiles.Healing if (player.whoAmI == Main.myPlayer) { CalamityPlayer calPlayer = player.Calamity(); - calPlayer.phantomicHeartRegen = 720; + calPlayer.phantomicHeartRegen = 600; Projectile.Kill(); } } diff --git a/Projectiles/Summon/HallowedStarSummon.cs b/Projectiles/Summon/HallowedStarSummon.cs index 7875876023..12f84ae24b 100644 --- a/Projectiles/Summon/HallowedStarSummon.cs +++ b/Projectiles/Summon/HallowedStarSummon.cs @@ -29,6 +29,8 @@ namespace CalamityMod.Projectiles.Summon Projectile.penetrate = 1; Projectile.tileCollide = false; Projectile.DamageType = DamageClass.Summon; + Projectile.extraUpdates = 4; + Projectile.stopsDealingDamageAfterPenetrateHits = true; } public override void AI() diff --git a/Projectiles/Summon/PhantomicDagger.cs b/Projectiles/Summon/PhantomicDagger.cs index 114b11ab6c..8831c83389 100644 --- a/Projectiles/Summon/PhantomicDagger.cs +++ b/Projectiles/Summon/PhantomicDagger.cs @@ -57,11 +57,6 @@ namespace CalamityMod.Projectiles.Summon if (target.defense > 999 || target.Calamity().DR >= 0.95f || target.Calamity().unbreakableDR) return; - int cap = 3; - float capDamageFactor = 0.05f; - int excessCount = Main.player[Projectile.owner].ownedProjectileCounts[Type] - cap; - modifiers.SourceDamage *= MathHelper.Clamp(1f - (capDamageFactor * excessCount), 0f, 1f); - // Bypass a portion of the target's DR float maxDRPenetration = 1.05f; // 5% extra damage modifiers.FinalDamage *= MathHelper.Clamp(1f / (1f - target.Calamity().DR), 1f, maxDRPenetration); @@ -111,16 +106,15 @@ namespace CalamityMod.Projectiles.Summon } if (Projectile.alpha != 0) { - Projectile.rotation -= 0.25f; - Projectile.velocity.X *= 0.985f; - Projectile.velocity.Y *= 0.985f; + Projectile.rotation -= 6f * (MathF.Pow(Projectile.Opacity,2f)); + Projectile.velocity *= MathHelper.Lerp(1, 0.9f, Projectile.Opacity); if (Projectile.alpha < 3) { Projectile.alpha = 0; homing = true; } else - Projectile.alpha -= 3; + Projectile.alpha -= 2; } else { @@ -139,8 +133,8 @@ namespace CalamityMod.Projectiles.Summon targetDist = projVel / targetDist; targetXDist *= targetDist; targetYDist *= targetDist; - Projectile.velocity.X = (Projectile.velocity.X * 25f + targetXDist) / 26f; - Projectile.velocity.Y = (Projectile.velocity.Y * 25f + targetYDist) / 26f; + Projectile.velocity.X = (Projectile.velocity.X * 2f + targetXDist) / 3f; + Projectile.velocity.Y = (Projectile.velocity.Y * 2f + targetYDist) / 3f; } else { From 530931b04e61a65cf055bb1612d839f46246f387 Mon Sep 17 00:00:00 2001 From: Big E Date: Sat, 27 Dec 2025 00:08:35 -0500 Subject: [PATCH 05/53] + Progress --- NPCs/CalamityVanillaAIOverrideNPC.cs | 6 ++- .../Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs | 35 +++++++++++--- .../Bosses/BrainOfCthulhu/CreeperAI.cs | 46 ++++++++----------- .../VanillaAIOverride.cs | 1 + 4 files changed, 52 insertions(+), 36 deletions(-) diff --git a/NPCs/CalamityVanillaAIOverrideNPC.cs b/NPCs/CalamityVanillaAIOverrideNPC.cs index 49fb2963e2..353c355c11 100644 --- a/NPCs/CalamityVanillaAIOverrideNPC.cs +++ b/NPCs/CalamityVanillaAIOverrideNPC.cs @@ -921,12 +921,14 @@ public sealed partial class CalamityVanillaAIOverrideNPC : GlobalNPC result &= GlobalPreAI(npc); if (AIOverride != null) { + result &= AIOverride.AI(Mod); + if (AIOverride.DisableMultiplayerSmoothing) { npc.netOffset = Vector2.Zero; + if (AIOverride.EnableMultiplayerSmoothingAheadOfAI) + AIOverride.DisableMultiplayerSmoothing = false; } - - result &= AIOverride.AI(Mod); } return result; } diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs index 1aba67f9bc..a0d7d24e8c 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs @@ -10,6 +10,7 @@ using CalamityMod.Particles; using CalamityMod.Projectiles.Boss.BrainOfCthulhu; using CalamityMod.Utilities.Daybreak; using CalamityMod.World; +using Microsoft.CodeAnalysis; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; @@ -263,10 +264,10 @@ public class BrainOfCthulhuAI : VanillaAIOverride private static float CreeperAmountRatio => NPC.CountNPCS(NPCID.Creeper) / (float)GetBrainOfCthuluCreepersCountRevDeath(); + public override bool EnableMultiplayerSmoothingAheadOfAI => true; + public override void SetDefaults(Mod mod) { - DisableMultiplayerSmoothing = true; - BoCDrawOffset = Vector2.Zero; ShieldOpacity = 1f; ShieldScale = 1f; @@ -290,8 +291,6 @@ public class BrainOfCthulhuAI : VanillaAIOverride public override void OnSpawn(Mod mod) { - DisableMultiplayerSmoothing = true; - if (NPC.target < 0 || NPC.target == Main.maxPlayers || Main.player[NPC.target].dead || !Main.player[NPC.target].active) { // Ignore tank players, target low HP players, Brain is smart @@ -304,6 +303,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride bool onSurface = target.Center.Y / 16 < Main.worldSurface; NPC.Center = target.Center + Vector2.UnitY * (onSurface ? 900 : -900); + DisableMultiplayerSmoothing = true; NPC.dontTakeDamage = true; AIState = onSurface ? BrainAIState.SurfaceSpawnAnimation : BrainAIState.UndergroundSpawnAnimation; @@ -342,8 +342,6 @@ public class BrainOfCthulhuAI : VanillaAIOverride else NPC.damage = NPC.defDamage; - bool death = CalamityWorld.death || BossRushEvent.BossRushActive; - #region Targeting if (NPC.target < 0 || NPC.target == Main.maxPlayers || Main.player[NPC.target].dead || !Main.player[NPC.target].active) { @@ -617,7 +615,10 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (AttackCounter < GetBrainOfCthuluCreepersCountRevDeath()) { if (SpawnTime == 0) + { NPC.Center = Target.Center + Vector2.UnitY * (AIState == BrainAIState.UndergroundSpawnAnimation ? -900 : 900); + DisableMultiplayerSmoothing = true; + } if (SpawnDelay <= 0) { @@ -1328,6 +1329,17 @@ public class BrainOfCthulhuAI : VanillaAIOverride } } + if (Time < OrbitSetupDuration) + { + AttackPosition = Target.Center; + } + else + { + float prox = Target.DistanceSQ(AttackPosition); + if (prox > 65536) //256^2 + AttackPosition += Target.DirectionFrom(AttackPosition) * (((float)Math.Sqrt(prox) - 256) / 16f); + } + if (Time >= OrbitDuration + 30) { Time = -1; @@ -1569,6 +1581,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride { Vector2 start = NPC.Center; NPC.Center = endPoint; + DisableMultiplayerSmoothing = true; AttackFlag = true; NPC.netUpdate = true; } @@ -1719,6 +1732,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride float waveValue = Time * MathHelper.Pi / BloodshotRate; Vector2 goalPos = Target.Center + new Vector2((float)Math.Cos(waveValue) * HoverDistance.X * AttackSign, (float)(-0.5f * Math.Cos(2 * waveValue) + 0.5f) * -HoverDistance.Y); NPC.velocity = Vector2.Zero; + DisableMultiplayerSmoothing = true; if (Time < 30f) NPC.Center = Vector2.Lerp(AttackPosition, goalPos, CalamityUtils.SineOutEasing(Time / 30f, 1)); else @@ -1833,6 +1847,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride { Vector2 start = NPC.Center; NPC.Center = endPoint; + DisableMultiplayerSmoothing = true; AttackFlag = true; NPC.netUpdate = true; } @@ -2099,7 +2114,10 @@ public class BrainOfCthulhuAI : VanillaAIOverride float rot = AttackRotation + (CalamityWorld.death ? MathHelper.PiOver4 : MathHelper.PiOver2) * i; Vector2 spawnPos = AttackPosition + (rot.ToRotationVector2() * IllusionDashTeleportDistance); if (i == 0) + { NPC.Center = spawnPos; + DisableMultiplayerSmoothing = true; + } else if (Main.netMode != NetmodeID.MultiplayerClient) NPC.NewNPCDirect(NPC.GetSource_FromThis(), spawnPos, ModContent.NPCType(), 0, 15, 30, rot).netUpdate = true; } @@ -2140,11 +2158,12 @@ public class BrainOfCthulhuAI : VanillaAIOverride float circleDist = MathHelper.Lerp(IllusionDashTeleportDistance, IllusionDashCloseInDistance, CalamityUtils.SineOutEasing(lerp, 1)); NPC.Center = Vector2.Lerp(AttackPosition, Target.Center + (AttackRotation.ToRotationVector2() * circleDist), lerp); AttackRotation += MathHelper.Lerp(0f, IllusionDashStartingSpinSpeed, CalamityUtils.SineInEasing(lerp, 1)); + DisableMultiplayerSmoothing = true; } else if (startTime <= 30 + IllusionDashSpinDuration) { NPC.Center = Target.Center + AttackRotation.ToRotationVector2() * IllusionDashCloseInDistance; - + DisableMultiplayerSmoothing = true; AttackRotation += MathHelper.Lerp(IllusionDashStartingSpinSpeed, 0f, CalamityUtils.SineOutEasing((startTime - 30) / (float)IllusionDashSpinDuration, 1)); } else if (startTime < 30 + IllusionDashSpinDuration + 30) @@ -2198,6 +2217,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride { AttackFlag = true; NPC.Center = endPoint; + DisableMultiplayerSmoothing = true; } else { @@ -2379,6 +2399,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride NPC.Center = AttackPosition + Vector2.UnitX.RotatedBy(AttackRotation) * (baseDist + (circleDist * ((float)Math.Sin(-AttackTime * MathHelper.TwoPi / FalseBrain.TimeDivisor) / 2f + 0.5f))); NPC.Center += Vector2.UnitX.RotatedBy(AttackRotation + MathHelper.PiOver2) * (90 * (float)Math.Cos(AttackTime * MathHelper.TwoPi / FalseBrain.TimeDivisor)); NPC.Opacity = 1f; + DisableMultiplayerSmoothing = true; AttackCounter = 0; } } diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs index 049c25e75c..93397bd600 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs @@ -65,6 +65,8 @@ public class CreeperAI : VanillaAIOverride bool useBossAIState = true; + public override bool EnableMultiplayerSmoothingAheadOfAI => true; + public override bool AI(Mod mod) { #region Despawn @@ -329,6 +331,7 @@ public class CreeperAI : VanillaAIOverride goalLocation.X += MathHelper.Lerp(0f, 900f, CalamityUtils.SineInOutEasing(MathHelper.Clamp((Time - (brain.AIOverride().SwipeDelay + 5)) / 55f, 0f, 1f), 1)) * (handSide == -1 ? 1 : -1); NPC.Center = Vector2.Lerp(NPC.Center, goalLocation, MathHelper.Clamp((Time - brain.AIOverride().SwipeDelay) / 10f, 0f, 1f)); + DisableMultiplayerSmoothing = true; } Time++; @@ -340,7 +343,11 @@ public class CreeperAI : VanillaAIOverride if (brain.AIOverride().AttackList.Contains(NPC.whoAmI)) { if (Time < 0) + { Time = 0; + NPC.netUpdate = true; + AttackPosition = NPC.Center; + } } else { @@ -370,12 +377,11 @@ public class CreeperAI : VanillaAIOverride if (Time <= positioningTime) { - if (AttackPosition == Vector2.Zero) - AttackPosition = NPC.Center; Vector2 goalPosition = sharedTarget.Center - dashDir * 128; goalPosition += dashDir.RotatedBy(MathHelper.PiOver2) * 16; NPC.Center = Vector2.Lerp(AttackPosition, goalPosition, CalamityUtils.SineOutEasing(MathHelper.Clamp(Time / (float)LightSwipeTravelTime, 0f, 1f), 1)); NPC.velocity = Vector2.Zero; + DisableMultiplayerSmoothing = true; } else { @@ -423,6 +429,7 @@ public class CreeperAI : VanillaAIOverride Vector2 goalPosition = sharedTarget.Center - dashDir * 128; NPC.Center = Vector2.Lerp(AttackPosition, goalPosition, CalamityUtils.SineOutEasing(MathHelper.Clamp(Time / (float)StrongSwipeTravelTime, 0f, 1f), 1)); NPC.velocity = Vector2.Zero; + DisableMultiplayerSmoothing = true; } else { @@ -452,6 +459,7 @@ public class CreeperAI : VanillaAIOverride float moveDist = 196; NPC.Center = Vector2.Lerp(AttackPosition, AttackPosition + dashDir * moveDist, (Time - (positioningTime + reelbackTime)) / swingTime); NPC.velocity = Vector2.Zero; + DisableMultiplayerSmoothing = true; if (Time == (positioningTime + reelbackTime + swingTime)) { SoundEngine.PlaySound(SoundID.DD2_MonkStaffGroundImpact, NPC.Center); @@ -540,38 +548,21 @@ public class CreeperAI : VanillaAIOverride float slowDown = (1 - MathHelper.Clamp((bossCounter - OrbitDuration) / 30f, 0f, 1f)); AttackAngle += (BaseRotationSpeed * (MathHelper.Lerp(1f, 0.5f, CreeperAmountRatio) + (bocAI.OnSecondCreeperPhase ? 1f : 0.5f))) * slowDown * bocAI.AttackSign; Vector2 rotation = Vector2.UnitX.RotatedBy(CachedValue1 + AttackAngle) * dist; - Player target = Main.player[brain.target]; if (bossCounter < OrbitSetupDuration) { NPC.damage = 0; - + if (bossCounter == 0) AttackPosition = NPC.Center; - Vector2 goalLocation = target.Center + rotation; - if (bossCounter < OrbitSetupDuration) - NPC.Center = Vector2.Lerp(AttackPosition, goalLocation, CalamityUtils.SineOutEasing(bossCounter / OrbitSetupDuration, 1)); - else - NPC.Center = goalLocation; + NPC.Center = Vector2.Lerp(AttackPosition, bocAI.AttackPosition + rotation, CalamityUtils.SineOutEasing(bossCounter / OrbitSetupDuration, 1)); + DisableMultiplayerSmoothing = true; } else { NPC.damage = NPC.defDamage; - - if (bossCounter <= OrbitSetupDuration + 10) - { - float lerp = CalamityUtils.SineOutEasing((bossCounter - OrbitSetupDuration) / 10f, 1); - AttackPosition = Vector2.Lerp(target.Center, AttackPosition, lerp); - } - else - { - float prox = target.Distance(AttackPosition); - if (prox > 256) - AttackPosition += target.DirectionFrom(AttackPosition) * ((prox - 256) / 16f); - } - - Vector2 goalLocation = AttackPosition + rotation; - NPC.Center = goalLocation; + NPC.Center = bocAI.AttackPosition + rotation; + DisableMultiplayerSmoothing = true; } } @@ -581,11 +572,12 @@ public class CreeperAI : VanillaAIOverride if (bossCounter == 0) { - AttackPosition = Vector2.Zero; + AttackPosition = NPC.Center; List myGroup = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && (n.ai[0] % TendrilCount) + 1 == tendrilID).ToList(); CachedValue1 = myGroup.IndexOf(NPC); CachedValue2 = myGroup.Count; AttackAngle = 0; + NPC.netUpdate = true; } int index = (int)CachedValue1; @@ -606,6 +598,7 @@ public class CreeperAI : VanillaAIOverride if (bossCounter >= SpiralSetupTime) { NPC.Center = position; + DisableMultiplayerSmoothing = true; NPC.damage = NPC.defDamage; NPC.knockBackResist = 0f; @@ -616,11 +609,10 @@ public class CreeperAI : VanillaAIOverride NPC.velocity *= 0.66f; else { - if (AttackPosition == Vector2.Zero) - AttackPosition = NPC.Center; NPC.velocity = Vector2.Zero; float lerp = (bossCounter - (SpiralSetupTime / 10f)) / (float)(SpiralSetupTime * 0.9f); NPC.Center = Vector2.Lerp(AttackPosition, position, CalamityUtils.SineInOutEasing(MathHelper.Clamp(lerp, 0f, 1f), 1)); + DisableMultiplayerSmoothing = true; } } diff --git a/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs b/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs index f3317441c4..6fdff21321 100644 --- a/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs +++ b/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs @@ -12,6 +12,7 @@ namespace CalamityMod.NPCs.VanillaNPCAIOverrides { public NPC NPC { get; set; } public bool DisableMultiplayerSmoothing { get; set; } + public virtual bool EnableMultiplayerSmoothingAheadOfAI => false; public void Load(Mod mod) { From be38431e89c66ce7368d7d08764ab97683eaab9b Mon Sep 17 00:00:00 2001 From: Big E Date: Sat, 27 Dec 2025 15:38:16 -0500 Subject: [PATCH 06/53] + Multiplayer Fixes --- .../Bosses/BrainOfCthulhu/BrainIllusion.cs | 18 +- .../Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs | 167 ++++++++---------- .../BrainOfCthulhu/BrainOfCthulhuSystem.cs | 3 +- .../Bosses/BrainOfCthulhu/CreeperAI.cs | 44 ++--- .../Bosses/BrainOfCthulhu/FalseBrain.cs | 3 + .../BrainOfCthulhu/TelekineticEnemyGrab.cs | 16 +- 6 files changed, 122 insertions(+), 129 deletions(-) diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainIllusion.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainIllusion.cs index 25068326cc..6f210adc67 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainIllusion.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainIllusion.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -30,6 +31,8 @@ public class BrainIllusion : ModNPC, ILocalizedModType ref float TeleportTime => ref NPC.ai[3]; + private Vector2 OldPos = Vector2.zeroVector; + public override void SetStaticDefaults() { this.HideFromBestiary(); @@ -92,16 +95,17 @@ public class BrainIllusion : ModNPC, ILocalizedModType { if (Time == 30) { - NPC.oldPos[0] = NPC.Center; + OldPos = NPC.Center; TeleportTime = 0; AttackValue = 0; NPC.Opacity = 1f; + NPC.netUpdate = true; } if (Time < 60) { float lerp = (Time - 30) / 30f; float circleDist = MathHelper.Lerp(BrainOfCthulhuAI.IllusionDashTeleportDistance, BrainOfCthulhuAI.IllusionDashCloseInDistance, CalamityUtils.SineInOutEasing(lerp, 1)); - NPC.Center = Vector2.Lerp(NPC.oldPos[0], target.Center + (Angle.ToRotationVector2() * circleDist), lerp); + NPC.Center = Vector2.Lerp(OldPos, target.Center + (Angle.ToRotationVector2() * circleDist), lerp); Angle += MathHelper.Lerp(0f, BrainOfCthulhuAI.IllusionDashStartingSpinSpeed, CalamityUtils.SineInEasing(lerp, 1)); } else if (Time <= 60f + BrainOfCthulhuAI.IllusionDashSpinDuration) @@ -133,6 +137,16 @@ public class BrainIllusion : ModNPC, ILocalizedModType Time++; } + public override void SendExtraAI(BinaryWriter writer) + { + writer.WritePackedWorldPosition(OldPos); + } + + public override void ReceiveExtraAI(BinaryReader reader) + { + OldPos = reader.ReadPackedWorldPosition(); + } + public override void FindFrame(int frameHeight) { NPC.frameCounter += 1.0; diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs index a0d7d24e8c..e5f2e3ae2f 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs @@ -13,6 +13,7 @@ using CalamityMod.World; using Microsoft.CodeAnalysis; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Graphics.PackedVector; using ReLogic.Content; using Terraria; using Terraria.Audio; @@ -200,10 +201,10 @@ public class BrainOfCthulhuAI : VanillaAIOverride #endregion - internal enum BrainAIState + internal enum BrainAIState : byte { //Spawn Animation - UndergroundSpawnAnimation = -2, + UndergroundSpawnAnimation, SurfaceSpawnAnimation, //Phase 1 Phase1Idle, @@ -247,7 +248,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride internal bool AttackFlag = false; internal Vector2 AttackPosition = Vector2.Zero; internal List availableAttacks = []; - internal List AttackList = []; + internal List AttackList = []; private Player Target => Main.player[NPC.target]; @@ -337,7 +338,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride else NPC.defense = (int)(NPC.defDefense * Phase1DefenseMultiplier); - if (AIState < 0) + if (AIState <= BrainAIState.SurfaceSpawnAnimation) NPC.damage = 0; else NPC.damage = NPC.defDamage; @@ -393,7 +394,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride #endregion #region Forced State Changes - if (!phase2 && CreeperHPRatio == 0f && AIState != BrainAIState.Stunned && AIState >= 0) + if (!phase2 && CreeperHPRatio == 0f && AIState != BrainAIState.Stunned && AIState >= BrainAIState.Phase1Idle) { AIState = BrainAIState.Stunned; Time = 0; @@ -622,23 +623,21 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (SpawnDelay <= 0) { - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } - bool targetLeft = AttackCounter % 2 == 0; List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1 && n.AIOverride().CreeperID % 2 == (targetLeft ? 0 : 1)).ToList(); - int rand; if (creepers.Count > 0) + { rand = Main.rand.Next(creepers.Count); + foreach (NPC creeper in creepers) + creeper.netUpdate = true; + } else { creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1).ToList(); + foreach (NPC creeper in creepers) + creeper.netUpdate = true; rand = Main.rand.Next(creepers.Count); } @@ -722,12 +721,6 @@ public class BrainOfCthulhuAI : VanillaAIOverride creep.AIOverride().Time = -1; NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } } #endregion @@ -815,7 +808,22 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (Time <= 60) { if (Time == 0) + { SoundEngine.PlaySound(Roar, NPC.Center); + + foreach(NPC creeper in Main.ActiveNPCs) + { + if (creeper.type != NPCID.Creeper) + continue; + + CreeperAI ai = creeper.AIOverride(); + Vector2 dir = Vector2.UnitX.RotatedBy(Main.rand.NextFloat(-MathHelper.TwoPi / 3f, MathHelper.TwoPi / 3f)) * (ai.evenID ? -1 : 1); + ai.AttackAngle = dir.ToRotation(); + float rayDist = CalamityUtils.PreciseDistanceToTileCollisionHit(NPC.Center, ai.AttackAngle, 800, 4); + ai.AttackPosition = NPC.Center + (dir * (rayDist - 64)); + creeper.netUpdate = true; + } + } if (Time < 30) { BrainOfCthulhuSystem.ScreenBlurStrength = 0.5f; @@ -1134,7 +1142,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (AttackFlag || Npc.AIOverride().CreeperID % 2 == 0! ^ useEven) { - AttackList.Add(Npc.whoAmI); + AttackList.Add((byte)Npc.whoAmI); //Npc.AIOverride().Time = 0; anyActivated = true; } @@ -1146,7 +1154,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (Npc.type != NPCID.Creeper) continue; - AttackList.Add(Npc.whoAmI); + AttackList.Add((byte)Npc.whoAmI); //Npc.AIOverride().Time = 0; } @@ -1234,7 +1242,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (Time > delay) { - foreach (NPC creeper in Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1 && !AttackList.Contains(n.whoAmI))) + foreach (NPC creeper in Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1 && !AttackList.Contains((byte)n.whoAmI))) creeper.position += NPC.velocity; int crushCount; @@ -1253,7 +1261,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (Time < delay + attackDur && Time % attackDelay == 0) { - List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1 && !AttackList.Contains(n.whoAmI)).ToList(); + List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1 && !AttackList.Contains((byte)n.whoAmI)).ToList(); if (creepers.Count > 1) { float rotation; @@ -1269,15 +1277,17 @@ public class BrainOfCthulhuAI : VanillaAIOverride int rand = Main.rand.Next(creepers.Count); NPC first = creepers[rand]; + first.netUpdate = true; CreeperAI creeper1 = first.AIOverride(); - AttackList.Add(first.whoAmI); + AttackList.Add((byte)first.whoAmI); //creeper1.Time = 0; creeper1.AttackAngle = rotation; creepers.RemoveAt(rand); NPC second = creepers[Main.rand.Next(creepers.Count)]; + second.netUpdate = true; CreeperAI creeper2 = second.AIOverride(); - AttackList.Add(second.whoAmI); + AttackList.Add((byte)second.whoAmI); //creeper2.Time = 0; creeper2.AttackAngle = rotation + MathHelper.Pi; @@ -1286,12 +1296,6 @@ public class BrainOfCthulhuAI : VanillaAIOverride } NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } } if (Time > delay + attackDur + attackDelay) @@ -1299,8 +1303,6 @@ public class BrainOfCthulhuAI : VanillaAIOverride Time = 0; AIState = BrainAIState.Phase1Idle; AttackList.Clear(); - //foreach (NPC creep in Main.npc.Where(n => n.active && n.type == NPCID.Creeper)) - // creep.AIOverride().Time = -1; } } } @@ -1320,13 +1322,8 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (Time == 0) { AttackSign = Main.rand.NextBool() ? -1 : 1; + AttackPosition = Target.Center; NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } } if (Time < OrbitSetupDuration) @@ -1362,36 +1359,23 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (rand >= creepers.Count) rand -= creepers.Count; NPC creeper = creepers[rand]; - AttackList.Add(creeper.whoAmI); + AttackList.Add((byte)creeper.whoAmI); //creeper.AIOverride().Time = 0; rand += (int)Math.Round(creepers.Count / (float)OrbitAttackParticipantCount); } NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } } } } private void CreeperSpiral() { - if (Time == 0) { AttackSign = Main.rand.NextBool() ? -1 : 1; AttackRotation = 0; NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } } float startTimePerRev = MathHelper.Lerp(StartingTimePerRevolutionMax, StartingTimePerRevolutionMin, 1 - CreeperAmountRatio); float endTimePerRev = MathHelper.Lerp(EndingTimePerRevolutionMax, EndingTimePerRevolutionMin, 1 - CreeperAmountRatio); @@ -2304,13 +2288,6 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (AttackCounter == 0) { NPC.ShowNameOnHover = true; - foreach (NPC npc in Main.npc) - { - if (npc.type != ModContent.NPCType()) - continue; - npc.ModNPC().BeenHit = true; - } - NPC.velocity = NPC.DirectionFrom(Target.Center) * 8f; } else @@ -2336,7 +2313,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (p.Distance(NPC.Center) > DespawnRange) continue; - AttackList.Add(p.whoAmI); + AttackList.Add((byte)p.whoAmI); } foreach (NPC n in Main.ActiveNPCs) @@ -2536,13 +2513,19 @@ public class BrainOfCthulhuAI : VanillaAIOverride public override void SendExtraAI(BitWriter bitWriter, BinaryWriter binaryWriter) { - binaryWriter.Write((int)PreviousAttack); + binaryWriter.Write((byte)PreviousAttack); - binaryWriter.Write(TeleportTime); - binaryWriter.Write(TeleportDuration); + if (AIState == BrainAIState.Stunned || AIState >= BrainAIState.Phase2TransitionClosed) + { + binaryWriter.Write(TeleportTime); + binaryWriter.Write(TeleportDuration); + } - binaryWriter.Write(SpawnTime); - binaryWriter.Write(SpawnDelay); + if (AIState <= BrainAIState.SurfaceSpawnAnimation) + { + binaryWriter.Write(SpawnTime); + binaryWriter.Write(SpawnDelay); + } binaryWriter.Write(CachedRatio); @@ -2552,26 +2535,31 @@ public class BrainOfCthulhuAI : VanillaAIOverride binaryWriter.Write(AttackTime); binaryWriter.Write(AttackCounter); - binaryWriter.WritePackedVector2(AttackPosition); + binaryWriter.WritePackedWorldPosition(AttackPosition); - binaryWriter.Write(availableAttacks.Count); - for (int i = 0; i < availableAttacks.Count; i++) - binaryWriter.Write((int)availableAttacks[i]); + binaryWriter.Write((byte)availableAttacks.Count); - binaryWriter.Write(AttackList.Count); - for (int i = 0; i < AttackList.Count; i++) - binaryWriter.Write(AttackList[i]); + binaryWriter.Write(availableAttacks.Select(e => (byte)e).ToArray()); + + binaryWriter.Write((byte)AttackList.Count); + binaryWriter.Write(AttackList.ToArray()); } public override void ReceiveExtraAI(BitReader bitReader, BinaryReader binaryReader) { - PreviousAttack = (BrainAIState)binaryReader.ReadInt32(); + PreviousAttack = (BrainAIState)binaryReader.ReadByte(); - TeleportTime = binaryReader.ReadSingle(); - TeleportDuration = binaryReader.ReadSingle(); + if (AIState == BrainAIState.Stunned || AIState >= BrainAIState.Phase2TransitionClosed) + { + TeleportTime = binaryReader.ReadSingle(); + TeleportDuration = binaryReader.ReadSingle(); + } - SpawnTime = binaryReader.ReadSingle(); - SpawnDelay = binaryReader.ReadInt32(); + if (AIState <= BrainAIState.SurfaceSpawnAnimation) + { + SpawnTime = binaryReader.ReadSingle(); + SpawnDelay = binaryReader.ReadInt32(); + } CachedRatio = binaryReader.ReadSingle(); @@ -2581,17 +2569,13 @@ public class BrainOfCthulhuAI : VanillaAIOverride AttackTime = binaryReader.ReadSingle(); AttackCounter = binaryReader.ReadInt32(); - AttackPosition = binaryReader.ReadPackedVector2(); + AttackPosition = binaryReader.ReadPackedWorldPosition(); - int availableLength = binaryReader.ReadInt32(); - availableAttacks.Clear(); - for (int i = 0; i < availableLength; i++) - availableAttacks.Add((BrainAIState)binaryReader.ReadInt32()); + int availableLength = binaryReader.ReadByte(); + availableAttacks = binaryReader.ReadBytes(availableLength).Select(e => (BrainAIState)e).ToList(); - int attackLength = binaryReader.ReadInt32(); - AttackList.Clear(); - for (int i = 0; i < attackLength; i++) - AttackList.Add(binaryReader.ReadSingle()); + byte attackLength = binaryReader.ReadByte(); + AttackList = binaryReader.ReadBytes(attackLength).ToList(); } public override bool? CanBeHitByProjectile(Mod mod, Projectile projectile) @@ -2627,17 +2611,18 @@ public class BrainOfCthulhuAI : VanillaAIOverride AIState = BrainAIState.DeathAnimation; ResetAttackValues(); Time = 0; + NPC.netUpdate = true; return; } if (AIState == BrainAIState.IllusionTrick && Time < 960) + { AttackFlag = true; + NPC.netUpdate = true; + } } - public override bool PreKill(Mod mod) - { - return AIState == BrainAIState.DeathAnimation && !NPC.dontTakeDamage; - } + public override bool PreKill(Mod mod) => AIState == BrainAIState.DeathAnimation && !NPC.dontTakeDamage; public override void FindFrame(Mod mod, int frameHeight) { diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuSystem.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuSystem.cs index 90abd9d40a..a4cc06eb76 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuSystem.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuSystem.cs @@ -48,13 +48,12 @@ public class BrainOfCthulhuSystem : ModSystem { orig(self); - if (NPC.crimsonBoss == -1 || !CalamityWorld.revenge) + if (NPC.crimsonBoss == -1 || !CalamityWorld.revenge || !Main.npc[NPC.crimsonBoss].active || !Main.npc[NPC.crimsonBoss].TryGetAIOverride(out var brainAI)) return; if (previousMusic < 0 || previousMusic >= Main.musicFade.Length) return; - var brainAI = Main.npc[NPC.crimsonBoss].AIOverride(); // The last part leaves one frame at the end of the spawn animation where the boss music starts playing, so that it can be instantly maxed out if (brainAI.AIState < 0 && (brainAI.Time - Math.Abs(brainAI.SpawnTime) < 420)) { diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs index 93397bd600..29f9af959b 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs @@ -46,7 +46,7 @@ public class CreeperAI : VanillaAIOverride float bossCounter => bocAI.Time; - bool evenID => CreeperID % 2 == 0; + internal bool evenID => CreeperID % 2 == 0; int creeperCount { @@ -215,29 +215,18 @@ public class CreeperAI : VanillaAIOverride private void TelekineticOnslaught() { - if (Time == 0 || AttackPosition == Vector2.Zero) - { - Vector2 dir = Vector2.UnitX.RotatedBy(Main.rand.NextFloat(-MathHelper.TwoPi / 3f, MathHelper.TwoPi / 3f)) * (evenID ? -1 : 1); - AttackAngle = dir.ToRotation(); - float rayDist = CalamityUtils.PreciseDistanceToTileCollisionHit(brain.Center, AttackAngle, 800, 4); - AttackPosition = (dir * (rayDist - 64)); - NPC.netUpdate = true; - } - if (Time > 0) { - Vector2 goalLocation = brain.Center + AttackPosition; - - if (WorldGen.SolidOrSlopedTile(goalLocation.ToTileCoordinates().X, goalLocation.ToTileCoordinates().Y)) + Point tileCoords = AttackPosition.ToTileCoordinates(); + if (WorldGen.SolidOrSlopedTile(tileCoords.X, tileCoords.Y)) { float rayDist = CalamityUtils.PreciseDistanceToTileCollisionHit(brain.Center, AttackAngle, 800, 4); - AttackPosition = (AttackAngle.ToRotationVector2() * (rayDist - 64)); - goalLocation = brain.Center + AttackPosition; + AttackPosition = brain.Center + (AttackAngle.ToRotationVector2() * (rayDist - 64)); } - if (NPC.DistanceSQ(goalLocation) > 4096) + if (NPC.DistanceSQ(AttackPosition) > 4096) { - NPC.velocity += NPC.DirectionTo(goalLocation); + NPC.velocity += NPC.DirectionTo(AttackPosition); NPC.velocity = NPC.velocity.ClampMagnitude(0f, 10f); } else @@ -261,7 +250,7 @@ public class CreeperAI : VanillaAIOverride AIState = CreeperAIState.Idle; } - if (brain.AIOverride().AttackList.Contains(NPC.whoAmI)) + if (brain.AIOverride().AttackList.Contains((byte)NPC.whoAmI)) { if (Time < 0) Time = 0; @@ -340,7 +329,7 @@ public class CreeperAI : VanillaAIOverride private void CreeperSwings() { - if (brain.AIOverride().AttackList.Contains(NPC.whoAmI)) + if (brain.AIOverride().AttackList.Contains((byte)NPC.whoAmI)) { if (Time < 0) { @@ -410,7 +399,7 @@ public class CreeperAI : VanillaAIOverride { NPC.damage = 0; Time = -1; - brain.AIOverride().AttackList.Remove(NPC.whoAmI); + brain.AIOverride().AttackList.Remove((byte)NPC.whoAmI); AttackPosition = Vector2.Zero; ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0f); return; @@ -489,7 +478,7 @@ public class CreeperAI : VanillaAIOverride { NPC.damage = 0; Time = -1; - brain.AIOverride().AttackList.Remove(NPC.whoAmI); + brain.AIOverride().AttackList.Remove((byte)NPC.whoAmI); AttackPosition = Vector2.Zero; ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0.5f); return; @@ -508,13 +497,17 @@ public class CreeperAI : VanillaAIOverride { CachedValue1 = MathHelper.TwoPi / creeperCount * localCreeperID; AttackAngle = 0; + NPC.netUpdate = true; } float dist = OrbitStandardRadius + ((float)Math.Sin((CachedValue1 * 7) + bossCounter / 20f) * 24); - if (brain.AIOverride().AttackList.Contains(NPC.whoAmI)) + if (brain.AIOverride().AttackList.Contains((byte)NPC.whoAmI)) { if (Time < 0) + { Time = 0; + NPC.netUpdate = true; + } } else { @@ -536,7 +529,7 @@ public class CreeperAI : VanillaAIOverride if (Time > OrbitAttackInterval) { Time = -2; - brain.AIOverride().AttackList.Remove(NPC.whoAmI); + brain.AIOverride().AttackList.Remove((byte)NPC.whoAmI); } } ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f, 0.1f); @@ -695,8 +688,7 @@ public class CreeperAI : VanillaAIOverride binaryWriter.Write(CachedValue2); binaryWriter.Write(PartnerIndex); - binaryWriter.WritePackedVector2(AttackPosition); - + binaryWriter.WritePackedWorldPosition(AttackPosition); } public override void ReceiveExtraAI(BitReader bitReader, BinaryReader binaryReader) @@ -705,7 +697,7 @@ public class CreeperAI : VanillaAIOverride CachedValue2 = binaryReader.ReadInt32(); PartnerIndex = binaryReader.ReadInt32(); - AttackPosition = binaryReader.ReadPackedVector2(); + AttackPosition = binaryReader.ReadPackedWorldPosition(); } public override void HitEffect(Mod mod, NPC.HitInfo hit) diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/FalseBrain.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/FalseBrain.cs index 3fadf10671..5e7beed8f4 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/FalseBrain.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/FalseBrain.cs @@ -70,6 +70,9 @@ public class FalseBrain : ModNPC, ILocalizedModType NPC brain = Main.npc[NPC.crimsonBoss]; NPC.GivenName = brain.GivenOrTypeName + $": {brain.life}/{brain.lifeMax}"; + if (brain.AIOverride().AttackFlag) + BeenHit = true; + if (BeenHit) { NPC.dontTakeDamage = true; diff --git a/Projectiles/Boss/BrainOfCthulhu/TelekineticEnemyGrab.cs b/Projectiles/Boss/BrainOfCthulhu/TelekineticEnemyGrab.cs index 0676297cc8..7c69c9d96e 100644 --- a/Projectiles/Boss/BrainOfCthulhu/TelekineticEnemyGrab.cs +++ b/Projectiles/Boss/BrainOfCthulhu/TelekineticEnemyGrab.cs @@ -180,24 +180,26 @@ public class TelekineticEnemyGrab : ModProjectile, ILocalizedModType { writer.Write(throwSign); - writer.WritePackedVector2(throwPos); + writer.WriteVector2(throwPos); - writer.WritePackedVector2(holdPos); + writer.WriteVector2(holdPos); } public override void ReceiveExtraAI(BinaryReader reader) { throwSign = reader.ReadInt32(); - throwPos = reader.ReadPackedVector2(); + throwPos = reader.ReadVector2(); - holdPos = reader.ReadPackedVector2(); + holdPos = reader.ReadVector2(); } - public override bool OnTileCollide(Vector2 oldVelocity) + public override bool OnTileCollide(Vector2 oldVelocity) => true; + + public override void OnKill(int timeLeft) { Vector2 velocity = Projectile.velocity.RotatedBy(MathHelper.Pi) / 8f; - Vector2 pos = Projectile.Center; + Vector2 pos = Projectile.Center + Projectile.velocity; switch (enemyID) { @@ -236,8 +238,6 @@ public class TelekineticEnemyGrab : ModProjectile, ILocalizedModType SoundEngine.PlaySound(SoundID.NPCDeath2 with { Volume = 0.175f }, pos); break; } - - return true; } bool evenRed = false; From cb714b3d7d56fa7269bc8ce3d6a413324fcdcf20 Mon Sep 17 00:00:00 2001 From: Big E Date: Sun, 28 Dec 2025 00:12:46 -0500 Subject: [PATCH 07/53] + Added balancing value for Brain Illusion damage --- .../Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs index e5f2e3ae2f..39dd8f8055 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs @@ -46,6 +46,8 @@ public class BrainOfCthulhuAI : VanillaAIOverride #region Balancing Values + internal static int BrainIllusionDamage => 15; + #region Projectile Damage Values internal static int BloodShotDamage => 12; // 48 internal static int BloodScytheDamage => 12; // 48 @@ -2103,7 +2105,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride DisableMultiplayerSmoothing = true; } else if (Main.netMode != NetmodeID.MultiplayerClient) - NPC.NewNPCDirect(NPC.GetSource_FromThis(), spawnPos, ModContent.NPCType(), 0, 15, 30, rot).netUpdate = true; + NPC.NewNPCDirect(NPC.GetSource_FromThis(), spawnPos, ModContent.NPCType(), 0, BrainIllusionDamage, 30, rot).netUpdate = true; } NPC.netUpdate = true; From 74bba98039e29ef8d464d5f699571b79d5c90e54 Mon Sep 17 00:00:00 2001 From: Stephen Thiebaud Date: Sat, 27 Dec 2025 02:15:32 -0600 Subject: [PATCH 08/53] feat: deprecate managedrendertarget --- Graphics/ManagedRenderTarget.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Graphics/ManagedRenderTarget.cs b/Graphics/ManagedRenderTarget.cs index f69b815ca7..1c00036be6 100644 --- a/Graphics/ManagedRenderTarget.cs +++ b/Graphics/ManagedRenderTarget.cs @@ -9,6 +9,7 @@ namespace CalamityMod.Graphics /// Wrapper class for that safely handles resizing, unloading and auto-disposal if not currently in use to save /// on GPU memory. /// + [Obsolete("ManagedRenderTarget is obsolete; developers should use RenderTarget2Ds and RenderTargetLeases")] public class ManagedRenderTarget : IDisposable { private RenderTarget2D target; From 690bd2b72c232929b7e4271e681980c605066682 Mon Sep 17 00:00:00 2001 From: Stephen Thiebaud Date: Sat, 27 Dec 2025 02:57:53 -0600 Subject: [PATCH 09/53] feat: deprecate swapto and reimplement basic api surface of managedrendertarget with target pools --- Graphics/ManagedRenderTarget.cs | 204 ++++++++++-------- Graphics/RenderTargetManager.cs | 53 +---- .../Daybreak/Buffers/BuffersLoadingSystem.cs | 3 + Utilities/DrawingUtils.cs | 1 + 4 files changed, 117 insertions(+), 144 deletions(-) diff --git a/Graphics/ManagedRenderTarget.cs b/Graphics/ManagedRenderTarget.cs index 1c00036be6..6f144ab40d 100644 --- a/Graphics/ManagedRenderTarget.cs +++ b/Graphics/ManagedRenderTarget.cs @@ -1,115 +1,129 @@ using System; +using System.Collections.Generic; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; -namespace CalamityMod.Graphics +namespace CalamityMod.Graphics; + +internal sealed class ManagedRenderTargetPool : RenderTargetPool { - /// - /// Wrapper class for that safely handles resizing, unloading and auto-disposal if not currently in use to save - /// on GPU memory. - /// - [Obsolete("ManagedRenderTarget is obsolete; developers should use RenderTarget2Ds and RenderTargetLeases")] - public class ManagedRenderTarget : IDisposable + public new static ManagedRenderTargetPool Shared { get; } = new(); + + private static readonly List managedTargets = []; + + public override RenderTargetLease Rent(GraphicsDevice device, int width, int height, RenderTargetDescriptor descriptor) { - private RenderTarget2D target; + throw new InvalidOperationException("ManagedRenderTargetPool does not support directly leasing targets"); + } - public readonly RenderTargetCreationCondition CreationCondition; + public RenderTargetLease Register(ManagedRenderTarget managedTarget) + { + managedTargets.Add(managedTarget); + return new RenderTargetLease(managedTarget.CreationCondition(Main.screenWidth, Main.screenHeight), this); + } - public readonly bool ShouldResetUponScreenResize; + public override void Return(RenderTargetLease lease) + { + lease.Target.Dispose(); + } - public readonly bool ShouldAutoDispose; + public void Return(ManagedRenderTarget managedRt) + { + _ = managedTargets.Remove(managedRt); + Return(managedRt.lease); + } - public bool WaitingForFirstInitialization + public override void Dispose() + { + foreach (var target in managedTargets) { - get; - private set; - } = true; - - public bool IsUninitialized => target is null || target.IsDisposed; - - public bool IsDisposed - { - get; - private set; + target.Dispose(); } - /// - /// The actual instance that the wrapper contains. - /// - public RenderTarget2D Target + managedTargets.Clear(); + } + + internal void ResizeTargets() + { + foreach (var target in managedTargets) { - get + if (target.ShouldResetUponScreenResize) { - if (IsUninitialized) - { - target = CreationCondition(Main.screenWidth, Main.screenHeight); - WaitingForFirstInitialization = false; - IsDisposed = false; - } - - TimeSinceLastAccessed = 0; - return target; + target.lease.Target.Dispose(); + target.lease.Target = target.CreationCondition(Main.screenWidth, Main.screenHeight); } - private set => target = value; } - - public int Width => Target.Width; - - public int Height => Target.Height; - - public Vector2 Size => new(Width, Height); - - /// - /// How many frames since this target has been gotten. Used to dispose of unused targets for the sake of performance. - /// - public int TimeSinceLastAccessed; - - public delegate RenderTarget2D RenderTargetCreationCondition(int screenWidth, int screenHeight); - - // For some reason, adding more arguments to this constructor causes really low end pcs to crash in FNA. I cannot figure out why, so do not use them. - public static RenderTarget2D CreateScreenSizedTarget(int screenWidth, int screenHeight) => new(Main.instance.GraphicsDevice, screenWidth, screenHeight); - - public ManagedRenderTarget(bool shouldResetUponScreenResize, RenderTargetCreationCondition creationCondition, bool shouldAutoDispose = true) - { - ShouldResetUponScreenResize = shouldResetUponScreenResize; - CreationCondition = creationCondition; - ShouldAutoDispose = shouldAutoDispose; - RenderTargetManager.ManagedTargets.Add(this); - } - - /// - /// Sets the current render target to the provided one. - /// - /// The render target to swap to - /// The color to clear the screen with. Transparent by default - public void SwapTo(Color? flushColor = null) => Target.SwapTo(flushColor); - - /// - /// Automatically called by , do not call! - /// - public void Dispose() - { - if (IsDisposed) - return; - - IsDisposed = true; - target?.Dispose(); - GC.SuppressFinalize(this); - } - - /// - /// Automatically called by , do not call! - /// - public void Recreate(int screenWidth, int screenHeight) - { - Dispose(); - IsDisposed = false; - - target = CreationCondition(screenWidth, screenHeight); - TimeSinceLastAccessed = 0; - } - - public static implicit operator RenderTarget2D(ManagedRenderTarget target) => target.Target; } } + +[Obsolete("ManagedRenderTarget is obsolete; developers should use RenderTarget2Ds and RenderTargetLeases")] +public class ManagedRenderTarget : IDisposable +{ + internal RenderTargetLease lease; + + public readonly RenderTargetCreationCondition CreationCondition; + + public readonly bool ShouldResetUponScreenResize; + + public readonly bool ShouldAutoDispose; + + public bool WaitingForFirstInitialization => false; + + public bool IsUninitialized => false; + + public bool IsDisposed + { + get; + private set; + } + + /// + /// The actual instance that the wrapper contains. + /// + public RenderTarget2D Target => lease.Target; + + public int Width => Target.Width; + + public int Height => Target.Height; + + public Vector2 Size => new(Width, Height); + + public int TimeSinceLastAccessed; + + public delegate RenderTarget2D RenderTargetCreationCondition(int screenWidth, int screenHeight); + + [Obsolete("use ScreenspaceTargetPool")] + public static RenderTarget2D CreateScreenSizedTarget(int screenWidth, int screenHeight) => new(Main.instance.GraphicsDevice, screenWidth, screenHeight); + + public ManagedRenderTarget(bool shouldResetUponScreenResize, RenderTargetCreationCondition creationCondition, bool shouldAutoDispose = true) + { + ShouldResetUponScreenResize = shouldResetUponScreenResize; + CreationCondition = creationCondition; + ShouldAutoDispose = shouldAutoDispose; + lease = ManagedRenderTargetPool.Shared.Register(this); + } + + /// + /// Sets the current render target to the provided one. + /// + /// The render target to swap to + /// The color to clear the screen with. Transparent by default + [Obsolete("Use RenderTargetScope")] + public void SwapTo(Color? flushColor = null) => Target.SwapTo(flushColor); + + public void Dispose() + { + if (IsDisposed) + return; + + IsDisposed = true; + ManagedRenderTargetPool.Shared.Return(this); + } + + // Does nothing + public void Recreate(int screenWidth, int screenHeight) { } + + public static implicit operator RenderTarget2D(ManagedRenderTarget target) => target.Target; +} diff --git a/Graphics/RenderTargetManager.cs b/Graphics/RenderTargetManager.cs index 56b673c968..52dd844c8c 100644 --- a/Graphics/RenderTargetManager.cs +++ b/Graphics/RenderTargetManager.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using Microsoft.Xna.Framework; using Terraria; using Terraria.ModLoader; @@ -8,10 +9,9 @@ namespace CalamityMod.Graphics /// /// Manager class that handles all created instances of /// + [Obsolete("ManagedRenderTarget is obsolete; developers should use RenderTarget2Ds and RenderTargetLeases")] public class RenderTargetManager : ModSystem { - internal static List ManagedTargets { get; } = []; - public delegate void RenderTargetUpdateDelegate(); /// @@ -24,64 +24,19 @@ namespace CalamityMod.Graphics /// public const int TimeBeforeAutoDispose = 600; - internal static void ResetTargetSizes(Vector2 screenSize) - { - foreach (ManagedRenderTarget target in ManagedTargets) - { - // Don't attempt to recreate targets that are already initialized or shouldn't be recreated. - if (target is null || target.IsDisposed || target.WaitingForFirstInitialization) - continue; - - Main.QueueMainThreadAction(() => - { - target.Recreate((int)screenSize.X, (int)screenSize.Y); - }); - } - } - - internal static void DisposeOfTargets() - { - Main.QueueMainThreadAction(() => - { - foreach (ManagedRenderTarget target in ManagedTargets) - target?.Dispose(); - ManagedTargets.Clear(); - }); - } - public override void OnModLoad() { Main.OnPreDraw += HandleTargetUpdateLoop; - Main.OnResolutionChanged += ResetTargetSizes; } public override void OnModUnload() { - DisposeOfTargets(); Main.OnPreDraw -= HandleTargetUpdateLoop; - Main.OnResolutionChanged -= ResetTargetSizes; - - if (RenderTargetUpdateLoopEvent != null) - { - foreach (var subscription in RenderTargetUpdateLoopEvent.GetInvocationList()) - RenderTargetUpdateLoopEvent -= (RenderTargetUpdateDelegate)subscription; - } + RenderTargetUpdateLoopEvent = null; } private void HandleTargetUpdateLoop(GameTime obj) { - // Auto-disposal of targets that havent been used in a while, to stop them hogging GPU memory. - foreach (ManagedRenderTarget target in ManagedTargets) - { - if (target == null || target.IsDisposed || !target.ShouldAutoDispose) - continue; - - if (target.TimeSinceLastAccessed >= TimeBeforeAutoDispose) - target.Dispose(); - else - target.TimeSinceLastAccessed++; - } - RenderTargetUpdateLoopEvent?.Invoke(); } } diff --git a/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs b/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs index 4d4abc310e..3e3b4292f4 100644 --- a/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs +++ b/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs @@ -1,3 +1,4 @@ +using CalamityMod.Graphics; using Terraria; using Terraria.ModLoader; @@ -44,6 +45,7 @@ public class BuffersLoadingSystem : ModSystem // Dispose shared pools. RenderTargetPool.Shared.Dispose(); ScreenspaceTargetPool.Shared.Dispose(); + ManagedRenderTargetPool.Shared.Dispose(); } ); } @@ -62,5 +64,6 @@ public class BuffersLoadingSystem : ModSystem orig(self); ScreenspaceTargetPool.Shared.ResizeCachedTargets(self.GraphicsDevice); + ManagedRenderTarget.Shared.ResizeTargets(); } } diff --git a/Utilities/DrawingUtils.cs b/Utilities/DrawingUtils.cs index 362d3fc71e..6941342c23 100644 --- a/Utilities/DrawingUtils.cs +++ b/Utilities/DrawingUtils.cs @@ -818,6 +818,7 @@ namespace CalamityMod /// /// The render target to swap to /// The color to clear the screen with. Transparent by default + [Obsolete("Use RenderTargetScope")] public static void SwapTo(this RenderTarget2D target, Color? flushColor = null) { // If we are in the menu, a server, or any of these are null, return. From b1e5333d7c1a22a6b974c74924dac504c18cd088 Mon Sep 17 00:00:00 2001 From: Stephen Thiebaud Date: Sat, 27 Dec 2025 03:16:14 -0600 Subject: [PATCH 10/53] fix: some race conditions and collection issues --- Graphics/ManagedRenderTarget.cs | 17 +++++++++++++---- Graphics/Renderers/BaseRenderer.cs | 9 ++++++++- .../Daybreak/Buffers/BuffersLoadingSystem.cs | 2 +- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/Graphics/ManagedRenderTarget.cs b/Graphics/ManagedRenderTarget.cs index 6f144ab40d..47f563979f 100644 --- a/Graphics/ManagedRenderTarget.cs +++ b/Graphics/ManagedRenderTarget.cs @@ -29,9 +29,13 @@ internal sealed class ManagedRenderTargetPool : RenderTargetPool lease.Target.Dispose(); } - public void Return(ManagedRenderTarget managedRt) + public void Return(ManagedRenderTarget managedRt, bool preserveCollection) { - _ = managedTargets.Remove(managedRt); + if (!preserveCollection) + { + _ = managedTargets.Remove(managedRt); + } + Return(managedRt.lease); } @@ -39,7 +43,7 @@ internal sealed class ManagedRenderTargetPool : RenderTargetPool { foreach (var target in managedTargets) { - target.Dispose(); + target.Dispose(preserveCollection: true); } managedTargets.Clear(); @@ -114,12 +118,17 @@ public class ManagedRenderTarget : IDisposable public void SwapTo(Color? flushColor = null) => Target.SwapTo(flushColor); public void Dispose() + { + Dispose(preserveCollection: false); + } + + public void Dispose(bool preserveCollection) { if (IsDisposed) return; IsDisposed = true; - ManagedRenderTargetPool.Shared.Return(this); + ManagedRenderTargetPool.Shared.Return(this, preserveCollection); } // Does nothing diff --git a/Graphics/Renderers/BaseRenderer.cs b/Graphics/Renderers/BaseRenderer.cs index cb1e3dc5a8..d513d99016 100644 --- a/Graphics/Renderers/BaseRenderer.cs +++ b/Graphics/Renderers/BaseRenderer.cs @@ -2,6 +2,7 @@ using CalamityMod.Enums; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using Terraria; using Terraria.ModLoader; namespace CalamityMod.Graphics.Renderers @@ -46,7 +47,13 @@ namespace CalamityMod.Graphics.Renderers public sealed override void SetupContent() => SetStaticDefaults(); - public sealed override void SetStaticDefaults() => MainTarget = new(true, ManagedRenderTarget.CreateScreenSizedTarget); + public sealed override void SetStaticDefaults() + { + Main.QueueMainThreadAction(() => + { + MainTarget = new(true, ManagedRenderTarget.CreateScreenSizedTarget); + }); + } /// /// Called from . diff --git a/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs b/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs index 3e3b4292f4..5639dba82e 100644 --- a/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs +++ b/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs @@ -64,6 +64,6 @@ public class BuffersLoadingSystem : ModSystem orig(self); ScreenspaceTargetPool.Shared.ResizeCachedTargets(self.GraphicsDevice); - ManagedRenderTarget.Shared.ResizeTargets(); + ManagedRenderTargetPool.Shared.ResizeTargets(); } } From 8c05732838c20333453bbb98a9b4d62c6274be09 Mon Sep 17 00:00:00 2001 From: Stephen Thiebaud Date: Sat, 27 Dec 2025 03:29:35 -0600 Subject: [PATCH 11/53] feat: initial removal of every reference to managedrendertarget --- Backgrounds/SunkenSeaBurrowsBG.cs | 5 +- FluidSimulation/FluidField.cs | 20 ++++---- FluidSimulation/FluidFieldState.cs | 5 +- Graphics/Metaballs/Metaball.cs | 5 +- Graphics/Metaballs/MetaballManager.cs | 2 +- .../Primitives/PrimitivePixelationSystem.cs | 39 ++++++++------- Graphics/Renderers/BaseRenderer.cs | 5 +- .../DyeableShadersRenderer.cs | 5 +- Particles/DeathAshParticle.cs | 5 +- Systems/Graphic/DoGVisualsManager.cs | 23 ++++----- .../PixelationSystem/PixelationManager.cs | 48 +++++++++---------- 11 files changed, 82 insertions(+), 80 deletions(-) diff --git a/Backgrounds/SunkenSeaBurrowsBG.cs b/Backgrounds/SunkenSeaBurrowsBG.cs index 4c80584980..875052949b 100644 --- a/Backgrounds/SunkenSeaBurrowsBG.cs +++ b/Backgrounds/SunkenSeaBurrowsBG.cs @@ -1,5 +1,6 @@ using CalamityMod.Graphics; using CalamityMod.Systems.Graphic; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; @@ -12,7 +13,7 @@ namespace CalamityMod.Backgrounds { public class SunkenSeaBurrowsBG : ModSystem { - private static ManagedRenderTarget WaterDistortionTarget; + private static RenderTargetLease WaterDistortionTarget; private static bool CurrentlyRendering { get; set; } @@ -26,7 +27,7 @@ namespace CalamityMod.Backgrounds GeneralDrawLayerSystem.OnPrepareDraw += DrawToTarget; On_Main.DrawBackgroundBlackFill += On_Main_DrawBackgroundBlackFill; - Main.QueueMainThreadAction(() => WaterDistortionTarget = new(true, ManagedRenderTarget.CreateScreenSizedTarget)); + Main.QueueMainThreadAction(() => WaterDistortionTarget = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice)); } public override void Unload() diff --git a/FluidSimulation/FluidField.cs b/FluidSimulation/FluidField.cs index 465a2f9de7..cfc1b8c1f6 100644 --- a/FluidSimulation/FluidField.cs +++ b/FluidSimulation/FluidField.cs @@ -1,6 +1,7 @@ using System; using CalamityMod.Effects; using CalamityMod.Graphics; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -12,11 +13,11 @@ namespace CalamityMod.FluidSimulation // Please do not change this system too much without contacting me first. -Dominic public class FluidField : IDisposable { - internal ManagedRenderTarget TemporaryAuxilaryTarget; + internal RenderTargetLease TemporaryAuxilaryTarget; - internal ManagedRenderTarget DivergenceField; + internal RenderTargetLease DivergenceField; - internal ManagedRenderTarget DivergencePoissonField; + internal RenderTargetLease DivergencePoissonField; internal FluidFieldState VelocityField; @@ -24,7 +25,7 @@ namespace CalamityMod.FluidSimulation internal FluidFieldState ColorField; - internal ManagedRenderTarget OutputTarget; + internal RenderTargetLease OutputTarget; public float Viscosity; @@ -71,8 +72,7 @@ namespace CalamityMod.FluidSimulation } // A surface format of Vector4 is used here to allow for both 0-1 ranged colors and other things at the same time. - public RenderTarget2D FluidCreateCondition(int screen, int height) => - new(Main.instance.GraphicsDevice, Size, Size, true, SurfaceFormat.Vector4, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + public static RenderTargetDescriptor FluidDescriptor => new RenderTargetDescriptor(SurfaceFormat.Vector4, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents, true); internal FluidField(int size, float scale, float viscosity, float diffusionFactor, float dissipationFactor) { @@ -86,12 +86,12 @@ namespace CalamityMod.FluidSimulation DensityField = new(size); ColorField = new(size); - TemporaryAuxilaryTarget = new(false, FluidCreateCondition, false); + TemporaryAuxilaryTarget = RenderTargetPool.Shared.Rent(Main.instance.GraphicsDevice, Size, Size, FluidDescriptor); - DivergenceField = new(false, FluidCreateCondition, false); - DivergencePoissonField = new(false, FluidCreateCondition, false); + DivergenceField = RenderTargetPool.Shared.Rent(Main.instance.GraphicsDevice, Size, Size, FluidDescriptor); + DivergencePoissonField = RenderTargetPool.Shared.Rent(Main.instance.GraphicsDevice, Size, Size, FluidDescriptor); - OutputTarget = new(false, FluidCreateCondition, false); + OutputTarget = RenderTargetPool.Shared.Rent(Main.instance.GraphicsDevice, Size, Size, FluidDescriptor); } internal void ApplyThingToTarget(RenderTarget2D currentField, Action shaderPreparationsAction) diff --git a/FluidSimulation/FluidFieldState.cs b/FluidSimulation/FluidFieldState.cs index 3036565049..9a807d250e 100644 --- a/FluidSimulation/FluidFieldState.cs +++ b/FluidSimulation/FluidFieldState.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using CalamityMod.Graphics; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -8,9 +9,9 @@ namespace CalamityMod.FluidSimulation // Calculations for these are done primarily on the GPU in shaders for performance-sake. public class FluidFieldState { - public ManagedRenderTarget PreviousState; + public RenderTargetLease PreviousState; - public ManagedRenderTarget NextState; + public RenderTargetLease NextState; public Queue PendingChanges = new(); diff --git a/Graphics/Metaballs/Metaball.cs b/Graphics/Metaballs/Metaball.cs index 1a75123c45..521eaebab2 100644 --- a/Graphics/Metaballs/Metaball.cs +++ b/Graphics/Metaballs/Metaball.cs @@ -2,6 +2,7 @@ using System.Linq; using CalamityMod.Effects; using CalamityMod.Enums; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -11,7 +12,7 @@ namespace CalamityMod.Graphics.Metaballs { public abstract class Metaball : ModType { - internal List LayerTargets = new(); + internal List LayerTargets = new(); /// /// Required utility that is used to determine whether this metaball has anything to draw.

@@ -145,7 +146,7 @@ namespace CalamityMod.Graphics.Metaballs // Load render targets. int layerCount = Layers.Count(); for (int i = 0; i < layerCount; i++) - LayerTargets.Add(new(true, ManagedRenderTarget.CreateScreenSizedTarget)); + LayerTargets.Add(ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice)); }); } diff --git a/Graphics/Metaballs/MetaballManager.cs b/Graphics/Metaballs/MetaballManager.cs index c33bb5f83f..868291d0cf 100644 --- a/Graphics/Metaballs/MetaballManager.cs +++ b/Graphics/Metaballs/MetaballManager.cs @@ -70,7 +70,7 @@ namespace CalamityMod.Graphics.Metaballs metaball.PrepareSpriteBatch(Main.spriteBatch); // Draw the raw contents of the metaball to each of its render targets. - foreach (ManagedRenderTarget target in metaball.LayerTargets) + foreach (var target in metaball.LayerTargets) { gd.SetRenderTarget(target); gd.Clear(Color.Transparent); diff --git a/Graphics/Primitives/PrimitivePixelationSystem.cs b/Graphics/Primitives/PrimitivePixelationSystem.cs index 3fa1d49fbc..0a565f4cc2 100644 --- a/Graphics/Primitives/PrimitivePixelationSystem.cs +++ b/Graphics/Primitives/PrimitivePixelationSystem.cs @@ -2,6 +2,7 @@ using System.Linq; using CalamityMod.Enums; using CalamityMod.Systems.Graphic; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -12,25 +13,23 @@ namespace CalamityMod.Graphics.Primitives public class PrimitivePixelationSystem : ModSystem { #region Fields/Properties - private static ManagedRenderTarget PixelationTarget_BeforeAllTiles; + private static RenderTargetLease PixelationTarget_BeforeAllTiles; - private static ManagedRenderTarget PixelationTarget_BeforeSolidTiles; + private static RenderTargetLease PixelationTarget_BeforeSolidTiles; - private static ManagedRenderTarget PixelationTarget_BeforeNPCs; + private static RenderTargetLease PixelationTarget_BeforeNPCs; - private static ManagedRenderTarget PixelationTarget_AfterNPCs; + private static RenderTargetLease PixelationTarget_AfterNPCs; - private static ManagedRenderTarget PixelationTarget_BeforeProjectiles; + private static RenderTargetLease PixelationTarget_BeforeProjectiles; - private static ManagedRenderTarget PixelationTarget_AfterProjectiles; + private static RenderTargetLease PixelationTarget_AfterProjectiles; - private static ManagedRenderTarget PixelationTarget_AfterPlayers; + private static RenderTargetLease PixelationTarget_AfterPlayers; - private static ManagedRenderTarget PixelationTarget_AfterDusts; + private static RenderTargetLease PixelationTarget_AfterDusts; - private static ManagedRenderTarget PixelationTarget_AfterEverything; - - private static RenderTarget2D CreatePixelTarget(int width, int height) => new(Main.instance.GraphicsDevice, width / 2, height / 2); + private static RenderTargetLease PixelationTarget_AfterEverything; /// /// Whether the system is currently rendering any primitives. @@ -50,15 +49,15 @@ namespace CalamityMod.Graphics.Primitives Main.QueueMainThreadAction(() => { - PixelationTarget_BeforeAllTiles = new(true, CreatePixelTarget); - PixelationTarget_BeforeSolidTiles = new(true, CreatePixelTarget); - PixelationTarget_BeforeNPCs = new(true, CreatePixelTarget); - PixelationTarget_AfterNPCs = new(true, CreatePixelTarget); - PixelationTarget_BeforeProjectiles = new(true, CreatePixelTarget); - PixelationTarget_AfterProjectiles = new(true, CreatePixelTarget); - PixelationTarget_AfterPlayers = new(true, CreatePixelTarget); - PixelationTarget_AfterDusts = new(true, CreatePixelTarget); - PixelationTarget_AfterEverything = new(true, CreatePixelTarget); + PixelationTarget_BeforeAllTiles = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_BeforeSolidTiles = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_BeforeNPCs = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_AfterNPCs = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_BeforeProjectiles = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_AfterProjectiles = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_AfterPlayers = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_AfterDusts = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_AfterEverything = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); }); GeneralDrawLayerSystem.OnDrawLayer += DrawTargetScaled; diff --git a/Graphics/Renderers/BaseRenderer.cs b/Graphics/Renderers/BaseRenderer.cs index d513d99016..63c838e624 100644 --- a/Graphics/Renderers/BaseRenderer.cs +++ b/Graphics/Renderers/BaseRenderer.cs @@ -1,5 +1,6 @@ using System; using CalamityMod.Enums; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -26,7 +27,7 @@ namespace CalamityMod.Graphics.Renderers /// /// The target that the visual is drawn to. Automatically handled. /// - public ManagedRenderTarget MainTarget + public RenderTargetLease MainTarget { get; private set; @@ -51,7 +52,7 @@ namespace CalamityMod.Graphics.Renderers { Main.QueueMainThreadAction(() => { - MainTarget = new(true, ManagedRenderTarget.CreateScreenSizedTarget); + MainTarget = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); }); } diff --git a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs index 799922dd00..4bd0f8cc9c 100644 --- a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs +++ b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs @@ -3,6 +3,7 @@ using System.Linq; using CalamityMod.DataStructures; using CalamityMod.Enums; using CalamityMod.Utilities.Daybreak; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -14,7 +15,7 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers public class DyeableShadersRenderer : BaseRenderer { #region Fields/Properties - public static Dictionary Targets + public static Dictionary Targets { get; private set; @@ -131,7 +132,7 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers { // If it doesn't have a dictonary entry, create one. if (!Targets.ContainsKey(renderer)) - Main.QueueMainThreadAction(() => Targets[renderer] = new(true, ManagedRenderTarget.CreateScreenSizedTarget)); + Main.QueueMainThreadAction(() => Targets[renderer] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice)); }); // Mark this item as drawable this frame. diff --git a/Particles/DeathAshParticle.cs b/Particles/DeathAshParticle.cs index f600b156ca..899d77578b 100644 --- a/Particles/DeathAshParticle.cs +++ b/Particles/DeathAshParticle.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using CalamityMod.Graphics; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -10,7 +11,7 @@ namespace CalamityMod.Particles { public class DeathAshParticle { - internal static Dictionary PendingNPCsToDraw = new(); + internal static Dictionary PendingNPCsToDraw = new(); internal static BasicEffect basicShader = null; internal static VertexPositionColorTexture[] VertexCache = new VertexPositionColorTexture[PrimitiveBatchSize * 4]; internal static short[] IndexCache = new short[PrimitiveBatchSize * 6]; @@ -91,7 +92,7 @@ namespace CalamityMod.Particles return; VelOverride = velocityOverride; - PendingNPCsToDraw[npc] = new(true, ManagedRenderTarget.CreateScreenSizedTarget); + PendingNPCsToDraw[npc] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); } public static Dictionary GetColorCacheFromTexture(Texture2D texture, Rectangle? frame = null, bool pruneForEfficency = false) diff --git a/Systems/Graphic/DoGVisualsManager.cs b/Systems/Graphic/DoGVisualsManager.cs index 2dde39a0fe..3d2e47c722 100644 --- a/Systems/Graphic/DoGVisualsManager.cs +++ b/Systems/Graphic/DoGVisualsManager.cs @@ -1,14 +1,15 @@ -using CalamityMod.Effects; +using System.Linq; +using CalamityMod.Effects; using CalamityMod.Graphics; +using CalamityMod.Graphics.Metaballs; using CalamityMod.Skies; -using Microsoft.Xna.Framework.Graphics; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; using Terraria.GameContent; using Terraria.Graphics.Effects; -using Terraria; using Terraria.ModLoader; -using CalamityMod.Graphics.Metaballs; -using System.Linq; namespace CalamityMod.Systems.Graphic { @@ -35,17 +36,17 @@ namespace CalamityMod.Systems.Graphic /// /// The actual effects and contents seen inside the rift in the background of DoG's fight. /// - public static ManagedRenderTarget DistortionRiftBackgroundContentsTarget { get; private set; } + public static RenderTargetLease DistortionRiftBackgroundContentsTarget { get; private set; } /// /// The primitives used to make up the shape of the rift seen in the background of DoG's fight. /// - public static ManagedRenderTarget DistortionRiftPrimitivesTarget { get; private set; } + public static RenderTargetLease DistortionRiftPrimitivesTarget { get; private set; } /// /// The actual effects and contents seen inside of certain attacks used by DoG. Also used for DoG's distortion metaballs. /// - public static ManagedRenderTarget DistortionForegroundContentsTarget { get; private set; } + public static RenderTargetLease DistortionForegroundContentsTarget { get; private set; } public override void OnModLoad() { @@ -62,9 +63,9 @@ namespace CalamityMod.Systems.Graphic Main.QueueMainThreadAction(() => { - DistortionRiftBackgroundContentsTarget = new(true, ManagedRenderTarget.CreateScreenSizedTarget); - DistortionRiftPrimitivesTarget = new(true, ManagedRenderTarget.CreateScreenSizedTarget); - DistortionForegroundContentsTarget = new(true, ManagedRenderTarget.CreateScreenSizedTarget); + DistortionRiftBackgroundContentsTarget = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); + DistortionRiftPrimitivesTarget = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); + DistortionForegroundContentsTarget = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); }); RenderTargetManager.RenderTargetUpdateLoopEvent += PrepareTargets; } diff --git a/Systems/Graphic/PixelationSystem/PixelationManager.cs b/Systems/Graphic/PixelationSystem/PixelationManager.cs index 151add53f1..3860255897 100644 --- a/Systems/Graphic/PixelationSystem/PixelationManager.cs +++ b/Systems/Graphic/PixelationSystem/PixelationManager.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using CalamityMod.Enums; using CalamityMod.Graphics; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -12,15 +13,15 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem { public class PixelationManager : ModSystem { - private static Dictionary PixelTargets_BeforeAllTiles; - private static Dictionary PixelTargets_BeforeSolidTiles; - private static Dictionary PixelTargets_BeforeNPCs; - private static Dictionary PixelTargets_AfterNPCs; - private static Dictionary PixelTargets_BeforeProjectiles; - private static Dictionary PixelTargets_AfterProjectiles; - private static Dictionary PixelTargets_AfterPlayers; - private static Dictionary PixelTargets_AfterDusts; - private static Dictionary PixelTargets_AfterEverything; + private static Dictionary PixelTargets_BeforeAllTiles; + private static Dictionary PixelTargets_BeforeSolidTiles; + private static Dictionary PixelTargets_BeforeNPCs; + private static Dictionary PixelTargets_AfterNPCs; + private static Dictionary PixelTargets_BeforeProjectiles; + private static Dictionary PixelTargets_AfterProjectiles; + private static Dictionary PixelTargets_AfterPlayers; + private static Dictionary PixelTargets_AfterDusts; + private static Dictionary PixelTargets_AfterEverything; private static List ActivePixelatedDrawers_BeforeAllTiles; private static List ActivePixelatedDrawers_BeforeSolidTiles; @@ -51,11 +52,6 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem } } - /// - /// Creates a render target at a ratio of the screen's current dimensions based on . - /// - internal static RenderTarget2D CreatePixelTarget(int width, int height) => new(Main.graphics.GraphicsDevice, (int)(width * PixelationResolution), (int)(height * PixelationResolution)); - public override void Load() { if (Main.dedServ) @@ -168,7 +164,7 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem } } - private static void DrawCollectionsToTarget(Dictionary targetCollection, Matrix pixelationMatrix, List drawerCollection) + private static void DrawCollectionsToTarget(Dictionary targetCollection, Matrix pixelationMatrix, List drawerCollection) { foreach (var blendStateTargetPair in targetCollection) { @@ -221,9 +217,9 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem return drawerCollection; } - private static Dictionary ReturnAssociatedTargetCollection(GeneralDrawLayer drawLayer) + private static Dictionary ReturnAssociatedTargetCollection(GeneralDrawLayer drawLayer) { - Dictionary targetCollection = drawLayer switch + Dictionary targetCollection = drawLayer switch { GeneralDrawLayer.BeforeAllTiles => PixelTargets_BeforeAllTiles, GeneralDrawLayer.BeforeSolidTiles => PixelTargets_BeforeSolidTiles, @@ -245,47 +241,47 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem { case GeneralDrawLayer.BeforeAllTiles: if (!PixelTargets_BeforeAllTiles.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_BeforeAllTiles[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_BeforeAllTiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) break; case GeneralDrawLayer.BeforeSolidTiles: if (!PixelTargets_BeforeSolidTiles.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_BeforeSolidTiles[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_BeforeSolidTiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) break; case GeneralDrawLayer.BeforeNPCs: if (!PixelTargets_BeforeNPCs.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_BeforeNPCs[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_BeforeNPCs[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) break; case GeneralDrawLayer.AfterNPCs: if (!PixelTargets_AfterNPCs.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterNPCs[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_AfterNPCs[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) break; case GeneralDrawLayer.BeforeProjectiles: if (!PixelTargets_BeforeProjectiles.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_BeforeProjectiles[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_BeforeProjectiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) break; case GeneralDrawLayer.AfterProjectiles: if (!PixelTargets_AfterProjectiles.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterProjectiles[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_AfterProjectiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) break; case GeneralDrawLayer.AfterPlayers: if (!PixelTargets_AfterPlayers.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterPlayers[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_AfterPlayers[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) break; case GeneralDrawLayer.AfterDusts: if (!PixelTargets_AfterDusts.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterDusts[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_AfterDusts[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) break; case GeneralDrawLayer.AfterEverything: if (!PixelTargets_AfterEverything.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterEverything[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_AfterEverything[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; } } From 2af9c2209f819c0675074f0ba324dc6d63835e28 Mon Sep 17 00:00:00 2001 From: Stephen Thiebaud Date: Sat, 27 Dec 2025 03:35:12 -0600 Subject: [PATCH 12/53] fix: repair every immediately-obviously-safe rt reference --- FluidSimulation/FluidField.cs | 14 +++++++------- FluidSimulation/FluidFieldState.cs | 8 +++----- Graphics/Metaballs/DoGDistortionMetaball.cs | 2 +- Graphics/Metaballs/MetaballManager.cs | 2 +- Graphics/Renderers/BaseRenderer.cs | 2 +- .../DyeableShadersRenderer.cs | 4 ++-- .../CalamityRenderers/MiracleBlightRenderer.cs | 2 +- Skies/DoGSky.cs | 4 ++-- .../PixelationSystem/PixelationManager.cs | 18 +++++++++--------- 9 files changed, 27 insertions(+), 29 deletions(-) diff --git a/FluidSimulation/FluidField.cs b/FluidSimulation/FluidField.cs index cfc1b8c1f6..a4b01c9237 100644 --- a/FluidSimulation/FluidField.cs +++ b/FluidSimulation/FluidField.cs @@ -169,7 +169,7 @@ namespace CalamityMod.FluidSimulation diffusionFactor *= DeltaTime * Size; ApplyThingToTarget(field.NextState, () => { - Main.instance.GraphicsDevice.Textures[1] = field.PreviousState; + Main.instance.GraphicsDevice.Textures[1] = field.PreviousState.Target; CalamityShaders.FluidShaders.Value.Parameters["size"].SetValue(Size); CalamityShaders.FluidShaders.Value.Parameters["diffusionFactor"].SetValue(diffusionFactor); CalamityShaders.FluidShaders.Value.Parameters["handlingColors"].SetValue(colors); @@ -209,9 +209,9 @@ namespace CalamityMod.FluidSimulation { ApplyThingToTarget(DivergencePoissonField, () => { - Main.instance.GraphicsDevice.Textures[1] = DivergencePoissonField; + Main.instance.GraphicsDevice.Textures[1] = DivergencePoissonField.Target; Main.instance.GraphicsDevice.Textures[2] = velocities; - Main.instance.GraphicsDevice.Textures[4] = DivergenceField; + Main.instance.GraphicsDevice.Textures[4] = DivergenceField.Target; CalamityShaders.FluidShaders.Value.Parameters["size"].SetValue(Size); CalamityShaders.FluidShaders.Value.CurrentTechnique.Passes["PerformPoissonIterationPass"].Apply(); }); @@ -220,7 +220,7 @@ namespace CalamityMod.FluidSimulation ApplyThingToTarget(velocities, () => { Main.instance.GraphicsDevice.Textures[1] = velocities; - Main.instance.GraphicsDevice.Textures[3] = DivergencePoissonField; + Main.instance.GraphicsDevice.Textures[3] = DivergencePoissonField.Target; CalamityShaders.FluidShaders.Value.CurrentTechnique.Passes["ClearDivergencePass"].Apply(); }); } @@ -279,9 +279,9 @@ namespace CalamityMod.FluidSimulation Main.instance.GraphicsDevice.Clear(Color.Transparent); Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); - Main.instance.GraphicsDevice.Textures[5] = ColorField.NextState; + Main.instance.GraphicsDevice.Textures[5] = ColorField.NextState.Target; CalamityShaders.FluidShaders.Value.CurrentTechnique.Passes["DrawFluidPass"].Apply(); - Main.spriteBatch.Draw(DensityField.NextState, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, 1f, 0, 0f); + Main.spriteBatch.Draw(DensityField.NextState.Target, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, 1f, 0, 0f); Main.spriteBatch.End(); Main.instance.GraphicsDevice.SetRenderTarget(null); @@ -323,7 +323,7 @@ namespace CalamityMod.FluidSimulation shaderPreparations?.Invoke(OutputTarget); - Main.spriteBatch.Draw(OutputTarget, drawPosition, null, Color.White, 0f, OutputTarget.Size * 0.5f, Scale, 0, 0f); + Main.spriteBatch.Draw(OutputTarget.Target, drawPosition, null, Color.White, 0f, OutputTarget.Target.Size() * 0.5f, Scale, 0, 0f); Main.spriteBatch.End(); if (needsToCallEnd) diff --git a/FluidSimulation/FluidFieldState.cs b/FluidSimulation/FluidFieldState.cs index 9a807d250e..0e9da15fbb 100644 --- a/FluidSimulation/FluidFieldState.cs +++ b/FluidSimulation/FluidFieldState.cs @@ -21,9 +21,6 @@ namespace CalamityMod.FluidSimulation public void SwapState() => Utils.Swap(ref PreviousState, ref NextState); - public RenderTarget2D FieldColorCreateCondition(int screen, int height) => - new(Main.instance.GraphicsDevice, Size, Size, true, FieldContents, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); - public FluidFieldState(int size, SurfaceFormat fieldContents = SurfaceFormat.Color) { if (Main.dedServ) @@ -32,8 +29,9 @@ namespace CalamityMod.FluidSimulation Size = size; FieldContents = fieldContents; - PreviousState = new(false, FieldColorCreateCondition, false); - NextState = new(false, FieldColorCreateCondition, false); + var descriptor = new RenderTargetDescriptor(FieldContents, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents, true); + PreviousState = RenderTargetPool.Shared.Rent(Main.instance.GraphicsDevice, Size, Size, descriptor); + NextState = RenderTargetPool.Shared.Rent(Main.instance.GraphicsDevice, Size, Size, descriptor); } } } diff --git a/Graphics/Metaballs/DoGDistortionMetaball.cs b/Graphics/Metaballs/DoGDistortionMetaball.cs index 260f13a4a1..0c23deb9ae 100644 --- a/Graphics/Metaballs/DoGDistortionMetaball.cs +++ b/Graphics/Metaballs/DoGDistortionMetaball.cs @@ -74,7 +74,7 @@ namespace CalamityMod.Graphics.Metaballs metaballShader.Value.Parameters["edgeColor"]?.SetValue(EdgeColor.ToVector4()); metaballShader.Value.Parameters["singleFrameScreenOffset"]?.SetValue((Main.screenLastPosition - Main.screenPosition) / screenSize); - gd.Textures[1] = DoGVisualsManager.DistortionForegroundContentsTarget; + gd.Textures[1] = DoGVisualsManager.DistortionForegroundContentsTarget.Target; gd.SamplerStates[1] = SamplerState.LinearWrap; metaballShader.Value.CurrentTechnique.Passes[0].Apply(); diff --git a/Graphics/Metaballs/MetaballManager.cs b/Graphics/Metaballs/MetaballManager.cs index 868291d0cf..107f2dbeba 100644 --- a/Graphics/Metaballs/MetaballManager.cs +++ b/Graphics/Metaballs/MetaballManager.cs @@ -110,7 +110,7 @@ namespace CalamityMod.Graphics.Metaballs metaball.PrepareShaderForTarget(i); // Draw the metaball's raw contents with the shader. - Main.spriteBatch.Draw(metaball.LayerTargets[i], Vector2.Zero, Color.White); + Main.spriteBatch.Draw(metaball.LayerTargets[i].Target, Vector2.Zero, Color.White); } } diff --git a/Graphics/Renderers/BaseRenderer.cs b/Graphics/Renderers/BaseRenderer.cs index 63c838e624..cfbe060ec6 100644 --- a/Graphics/Renderers/BaseRenderer.cs +++ b/Graphics/Renderers/BaseRenderer.cs @@ -82,7 +82,7 @@ namespace CalamityMod.Graphics.Renderers /// Draw the target here. By default, just draws the target. /// /// - public virtual void DrawTarget(SpriteBatch spriteBatch) => spriteBatch.Draw(MainTarget, Vector2.Zero, Color.White); + public virtual void DrawTarget(SpriteBatch spriteBatch) => spriteBatch.Draw(MainTarget.Target, Vector2.Zero, Color.White); #endregion } } diff --git a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs index 4bd0f8cc9c..f24116799b 100644 --- a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs +++ b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs @@ -189,10 +189,10 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers // If it is dyeable, and a dye exists, apply it. This has null safety, as dyeShader can be null here. if (renderer.ShaderIsDyeable && Dyes.TryGetValue(renderer, out var dyeID) && dyeID > 0) - GameShaders.Armor.Apply(dyeID, null, new(target, Vector2.Zero, new Rectangle(0, 0, target.Width, target.Height), Color.White)); + GameShaders.Armor.Apply(dyeID, null, new(target.Target, Vector2.Zero, new Rectangle(0, 0, target.Target.Width, target.Target.Height), Color.White)); // Draw the assosiated target that has been drawn to. - spriteBatch.Draw(target, Vector2.Zero, Color.White with { A = 0 }); + spriteBatch.Draw(target.Target, Vector2.Zero, Color.White with { A = 0 }); } spriteBatch.End(); diff --git a/Graphics/Renderers/CalamityRenderers/MiracleBlightRenderer.cs b/Graphics/Renderers/CalamityRenderers/MiracleBlightRenderer.cs index 330a07e939..2c0fb4dcfa 100644 --- a/Graphics/Renderers/CalamityRenderers/MiracleBlightRenderer.cs +++ b/Graphics/Renderers/CalamityRenderers/MiracleBlightRenderer.cs @@ -95,7 +95,7 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers blightShader.UseOpacity(0.7f); blightShader.Apply(); - spriteBatch.Draw(MainTarget, Vector2.Zero, Color.White); + spriteBatch.Draw(MainTarget.Target, Vector2.Zero, Color.White); spriteBatch.End(); spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise); diff --git a/Skies/DoGSky.cs b/Skies/DoGSky.cs index f6d728e352..34f3f33673 100644 --- a/Skies/DoGSky.cs +++ b/Skies/DoGSky.cs @@ -415,8 +415,8 @@ namespace CalamityMod.Skies { // Impose the distortion rift contents onto the primitives via shader. var metaballShader = CalamityShaders.MetaballEdgeShader; - Texture2D distortionRiftContents = DoGVisualsManager.DistortionRiftBackgroundContentsTarget; - Texture2D distortionRift = DoGVisualsManager.DistortionRiftPrimitivesTarget; + Texture2D distortionRiftContents = DoGVisualsManager.DistortionRiftBackgroundContentsTarget.Target; + Texture2D distortionRift = DoGVisualsManager.DistortionRiftPrimitivesTarget.Target; Vector2 screenSize = new(Main.screenWidth, Main.screenHeight); diff --git a/Systems/Graphic/PixelationSystem/PixelationManager.cs b/Systems/Graphic/PixelationSystem/PixelationManager.cs index 3860255897..2a63f1ff3e 100644 --- a/Systems/Graphic/PixelationSystem/PixelationManager.cs +++ b/Systems/Graphic/PixelationSystem/PixelationManager.cs @@ -194,7 +194,7 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem Main.spriteBatch.Begin(default, keyValuePair.Key, SamplerState.PointClamp, DepthStencilState.None, Main.Rasterizer, null, Main.GameViewMatrix.TransformationMatrix); float targetScale = 1f / PixelationResolution; - Main.spriteBatch.Draw(keyValuePair.Value, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, targetScale, SpriteEffects.None, 0f); + Main.spriteBatch.Draw(keyValuePair.Value.Target, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, targetScale, SpriteEffects.None, 0f); Main.spriteBatch.End(); } } @@ -241,42 +241,42 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem { case GeneralDrawLayer.BeforeAllTiles: if (!PixelTargets_BeforeAllTiles.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_BeforeAllTiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) + Main.QueueMainThreadAction(() => PixelTargets_BeforeAllTiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.BeforeSolidTiles: if (!PixelTargets_BeforeSolidTiles.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_BeforeSolidTiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) + Main.QueueMainThreadAction(() => PixelTargets_BeforeSolidTiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.BeforeNPCs: if (!PixelTargets_BeforeNPCs.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_BeforeNPCs[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) + Main.QueueMainThreadAction(() => PixelTargets_BeforeNPCs[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.AfterNPCs: if (!PixelTargets_AfterNPCs.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterNPCs[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) + Main.QueueMainThreadAction(() => PixelTargets_AfterNPCs[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.BeforeProjectiles: if (!PixelTargets_BeforeProjectiles.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_BeforeProjectiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) + Main.QueueMainThreadAction(() => PixelTargets_BeforeProjectiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.AfterProjectiles: if (!PixelTargets_AfterProjectiles.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterProjectiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) + Main.QueueMainThreadAction(() => PixelTargets_AfterProjectiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.AfterPlayers: if (!PixelTargets_AfterPlayers.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterPlayers[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) + Main.QueueMainThreadAction(() => PixelTargets_AfterPlayers[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.AfterDusts: if (!PixelTargets_AfterDusts.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterDusts[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))) + Main.QueueMainThreadAction(() => PixelTargets_AfterDusts[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.AfterEverything: From 955756808dce5aef4109905277af6cac4978ed4c Mon Sep 17 00:00:00 2001 From: Stephen Thiebaud Date: Sat, 27 Dec 2025 03:38:58 -0600 Subject: [PATCH 13/53] feat: replace every usage of swapto --- Backgrounds/SunkenSeaBurrowsBG.cs | 20 +++++++------ .../Primitives/PrimitivePixelationSystem.cs | 14 +++++---- .../DyeableShadersRenderer.cs | 6 ++-- Systems/Graphic/DoGVisualsManager.cs | 30 ++++++++++--------- .../PixelationSystem/PixelationManager.cs | 23 +++++++------- 5 files changed, 51 insertions(+), 42 deletions(-) diff --git a/Backgrounds/SunkenSeaBurrowsBG.cs b/Backgrounds/SunkenSeaBurrowsBG.cs index 875052949b..1aa6f74ccf 100644 --- a/Backgrounds/SunkenSeaBurrowsBG.cs +++ b/Backgrounds/SunkenSeaBurrowsBG.cs @@ -140,19 +140,21 @@ namespace CalamityMod.Backgrounds } CurrentlyRendering = true; - WaterDistortionTarget.SwapTo(); - // 13MAY2025: fryzahh: Note that when other Sunken Sea backgrounds are implemented they should use this same system. - // Leaving this here for other programmers, in case I don't get to doing this myself. - Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, CalamityUtils.BackgroundMatrix); + using (WaterDistortionTarget.Scope()) + { + // 13MAY2025: fryzahh: Note that when other Sunken Sea backgrounds are implemented they should use this same system. + // Leaving this here for other programmers, in case I don't get to doing this myself. + Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, CalamityUtils.BackgroundMatrix); - DrawShoresBG(); - DrawBurrowsBG(); + DrawShoresBG(); + DrawBurrowsBG(); - Main.spriteBatch.End(); + Main.spriteBatch.End(); - Main.graphics.GraphicsDevice.SetRenderTarget(null); - CurrentlyRendering = false; + Main.graphics.GraphicsDevice.SetRenderTarget(null); + CurrentlyRendering = false; + } } private void On_Main_DrawBackgroundBlackFill(On_Main.orig_DrawBackgroundBlackFill orig, Main self) diff --git a/Graphics/Primitives/PrimitivePixelationSystem.cs b/Graphics/Primitives/PrimitivePixelationSystem.cs index 0a565f4cc2..fcf6196688 100644 --- a/Graphics/Primitives/PrimitivePixelationSystem.cs +++ b/Graphics/Primitives/PrimitivePixelationSystem.cs @@ -173,16 +173,18 @@ namespace CalamityMod.Graphics.Primitives private static void DrawPrimsToRenderTarget(RenderTarget2D renderTarget, GeneralDrawLayer layer, List pixelPrimitives) { // Swap to the target regardless, in order to clear any leftover content from last frame. Not doing this results in the final frame lingering once it stops rendering. - renderTarget.SwapTo(); - if (pixelPrimitives.Any()) + using (renderTarget.Scope()) { - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null); + if (pixelPrimitives.Any()) + { + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null); - foreach (var pixelPrimitiveDrawer in pixelPrimitives) - pixelPrimitiveDrawer.RenderPixelatedPrimitives(Main.spriteBatch, layer); + foreach (var pixelPrimitiveDrawer in pixelPrimitives) + pixelPrimitiveDrawer.RenderPixelatedPrimitives(Main.spriteBatch, layer); - Main.spriteBatch.End(); + Main.spriteBatch.End(); + } } } #endregion diff --git a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs index f24116799b..44fa25de22 100644 --- a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs +++ b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs @@ -165,8 +165,10 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers continue; // Swap to the assosiated target and call the interface method. - target.SwapTo(); - renderer.DrawDyeableShader(spriteBatch); + using (target.Scope()) + { + renderer.DrawDyeableShader(spriteBatch); + } } } diff --git a/Systems/Graphic/DoGVisualsManager.cs b/Systems/Graphic/DoGVisualsManager.cs index 3d2e47c722..f550bb7136 100644 --- a/Systems/Graphic/DoGVisualsManager.cs +++ b/Systems/Graphic/DoGVisualsManager.cs @@ -159,29 +159,31 @@ namespace CalamityMod.Systems.Graphic if (ShouldDrawToBackgroundTargets) { // Draw the background which'll be displayed inside the rift onto a render target. - DistortionRiftBackgroundContentsTarget.SwapTo(); - DrawDistortionRiftBackground(); + using (DistortionRiftBackgroundContentsTarget.Scope()) + { + DrawDistortionRiftBackground(); + } - Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearWrap, DepthStencilState.None, Main.Rasterizer, null, CalamityUtils.BackgroundMatrix); + using (DistortionRiftPrimitivesTarget.Scope()) + { + Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearWrap, DepthStencilState.None, Main.Rasterizer, null, CalamityUtils.BackgroundMatrix); - // Draw the primitives which comprise the rift to another render target. - DistortionRiftPrimitivesTarget.SwapTo(); - if (SkyManager.Instance["CalamityMod:DevourerofGodsHead"].IsActive()) - (SkyManager.Instance["CalamityMod:DevourerofGodsHead"] as DoGSky).DrawRiftToRenderTarget(); + // Draw the primitives which comprise the rift to another render target. + if (SkyManager.Instance["CalamityMod:DevourerofGodsHead"].IsActive()) + (SkyManager.Instance["CalamityMod:DevourerofGodsHead"] as DoGSky).DrawRiftToRenderTarget(); - Main.spriteBatch.End(); + Main.spriteBatch.End(); + } } if (ShouldDrawToForegroundTarget) { // Draw the background which'll be displayed for all distortion-related effects done in the foreground (same layer as the player). - DistortionForegroundContentsTarget.SwapTo(); - DrawDistortionForeground(); + using (DistortionForegroundContentsTarget.Scope()) + { + DrawDistortionForeground(); + } } - - // Reset the current render target at the end of the method once any targets are being drawn to. - if (ShouldDrawToForegroundTarget || ShouldDrawToBackgroundTargets) - Main.instance.GraphicsDevice.SetRenderTarget(null); } #region Distortion Background Drawing diff --git a/Systems/Graphic/PixelationSystem/PixelationManager.cs b/Systems/Graphic/PixelationSystem/PixelationManager.cs index 2a63f1ff3e..344ed4ccda 100644 --- a/Systems/Graphic/PixelationSystem/PixelationManager.cs +++ b/Systems/Graphic/PixelationSystem/PixelationManager.cs @@ -168,19 +168,20 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem { foreach (var blendStateTargetPair in targetCollection) { - blendStateTargetPair.Value.SwapTo(); - - Main.spriteBatch.Begin(default, blendStateTargetPair.Key, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, pixelationMatrix); - - // Select only drawers who match this target's BlendState. - var drawersByBlendState = drawerCollection.Where(d => d.DefaultBlendState == blendStateTargetPair.Key).ToList(); - if (drawersByBlendState.Count > 0) + using (blendStateTargetPair.Value.Scope()) { - foreach (PixelatedDrawer drawer in drawersByBlendState) - drawer.DrawAction.Invoke(pixelationMatrix); - } + Main.spriteBatch.Begin(default, blendStateTargetPair.Key, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, pixelationMatrix); - Main.spriteBatch.End(); + // Select only drawers who match this target's BlendState. + var drawersByBlendState = drawerCollection.Where(d => d.DefaultBlendState == blendStateTargetPair.Key).ToList(); + if (drawersByBlendState.Count > 0) + { + foreach (PixelatedDrawer drawer in drawersByBlendState) + drawer.DrawAction.Invoke(pixelationMatrix); + } + + Main.spriteBatch.End(); + } } drawerCollection.Clear(); From f84d82fc01b8162840ce6fb478283c07864f46aa Mon Sep 17 00:00:00 2001 From: Stephen Thiebaud Date: Sat, 27 Dec 2025 03:39:57 -0600 Subject: [PATCH 14/53] fix: clear scoped targets to match swapto behavior --- Backgrounds/SunkenSeaBurrowsBG.cs | 2 +- Graphics/Primitives/PrimitivePixelationSystem.cs | 2 +- .../Renderers/CalamityRenderers/DyeableShadersRenderer.cs | 2 +- Systems/Graphic/DoGVisualsManager.cs | 6 +++--- Systems/Graphic/PixelationSystem/PixelationManager.cs | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Backgrounds/SunkenSeaBurrowsBG.cs b/Backgrounds/SunkenSeaBurrowsBG.cs index 1aa6f74ccf..8a55b31db4 100644 --- a/Backgrounds/SunkenSeaBurrowsBG.cs +++ b/Backgrounds/SunkenSeaBurrowsBG.cs @@ -141,7 +141,7 @@ namespace CalamityMod.Backgrounds CurrentlyRendering = true; - using (WaterDistortionTarget.Scope()) + using (WaterDistortionTarget.Scope(clearColor: Color.Transparent)) { // 13MAY2025: fryzahh: Note that when other Sunken Sea backgrounds are implemented they should use this same system. // Leaving this here for other programmers, in case I don't get to doing this myself. diff --git a/Graphics/Primitives/PrimitivePixelationSystem.cs b/Graphics/Primitives/PrimitivePixelationSystem.cs index fcf6196688..30b3b504cf 100644 --- a/Graphics/Primitives/PrimitivePixelationSystem.cs +++ b/Graphics/Primitives/PrimitivePixelationSystem.cs @@ -174,7 +174,7 @@ namespace CalamityMod.Graphics.Primitives { // Swap to the target regardless, in order to clear any leftover content from last frame. Not doing this results in the final frame lingering once it stops rendering. - using (renderTarget.Scope()) + using (renderTarget.Scope(clearColor: Color.Transparent)) { if (pixelPrimitives.Any()) { diff --git a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs index 44fa25de22..60479a2908 100644 --- a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs +++ b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs @@ -165,7 +165,7 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers continue; // Swap to the assosiated target and call the interface method. - using (target.Scope()) + using (target.Scope(clearColor: Color.Transparent)) { renderer.DrawDyeableShader(spriteBatch); } diff --git a/Systems/Graphic/DoGVisualsManager.cs b/Systems/Graphic/DoGVisualsManager.cs index f550bb7136..fc913ca06a 100644 --- a/Systems/Graphic/DoGVisualsManager.cs +++ b/Systems/Graphic/DoGVisualsManager.cs @@ -159,12 +159,12 @@ namespace CalamityMod.Systems.Graphic if (ShouldDrawToBackgroundTargets) { // Draw the background which'll be displayed inside the rift onto a render target. - using (DistortionRiftBackgroundContentsTarget.Scope()) + using (DistortionRiftBackgroundContentsTarget.Scope(clearColor: Color.Transparent)) { DrawDistortionRiftBackground(); } - using (DistortionRiftPrimitivesTarget.Scope()) + using (DistortionRiftPrimitivesTarget.Scope(clearColor: Color.Transparent)) { Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearWrap, DepthStencilState.None, Main.Rasterizer, null, CalamityUtils.BackgroundMatrix); @@ -179,7 +179,7 @@ namespace CalamityMod.Systems.Graphic if (ShouldDrawToForegroundTarget) { // Draw the background which'll be displayed for all distortion-related effects done in the foreground (same layer as the player). - using (DistortionForegroundContentsTarget.Scope()) + using (DistortionForegroundContentsTarget.Scope(clearColor: Color.Transparent)) { DrawDistortionForeground(); } diff --git a/Systems/Graphic/PixelationSystem/PixelationManager.cs b/Systems/Graphic/PixelationSystem/PixelationManager.cs index 344ed4ccda..eb31a01187 100644 --- a/Systems/Graphic/PixelationSystem/PixelationManager.cs +++ b/Systems/Graphic/PixelationSystem/PixelationManager.cs @@ -168,7 +168,7 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem { foreach (var blendStateTargetPair in targetCollection) { - using (blendStateTargetPair.Value.Scope()) + using (blendStateTargetPair.Value.Scope(clearColor: Color.Transparent)) { Main.spriteBatch.Begin(default, blendStateTargetPair.Key, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, pixelationMatrix); From fda6dca5af6e9acc7b1f593c60e77a1f6bf684ad Mon Sep 17 00:00:00 2001 From: Stephen Thiebaud Date: Sat, 27 Dec 2025 03:49:14 -0600 Subject: [PATCH 15/53] feat: remove basically every direct call to setrendertarget --- Backgrounds/SunkenSeaBurrowsBG.cs | 5 +- FluidSimulation/FluidField.cs | 35 ++++++------- Graphics/Metaballs/MetaballManager.cs | 16 +++--- Graphics/Renderers/RendererManager.cs | 6 +-- .../LiquidSystem/ModLavaStyleSystem_RT.cs | 50 ++++++++++--------- .../TileMerging/TileBlendTexture_Baking.cs | 18 +++---- Utilities/DrawingUtils.cs | 17 +++---- 7 files changed, 70 insertions(+), 77 deletions(-) diff --git a/Backgrounds/SunkenSeaBurrowsBG.cs b/Backgrounds/SunkenSeaBurrowsBG.cs index 8a55b31db4..b8de0ce754 100644 --- a/Backgrounds/SunkenSeaBurrowsBG.cs +++ b/Backgrounds/SunkenSeaBurrowsBG.cs @@ -151,10 +151,9 @@ namespace CalamityMod.Backgrounds DrawBurrowsBG(); Main.spriteBatch.End(); - - Main.graphics.GraphicsDevice.SetRenderTarget(null); - CurrentlyRendering = false; } + + CurrentlyRendering = false; } private void On_Main_DrawBackgroundBlackFill(On_Main.orig_DrawBackgroundBlackFill orig, Main self) diff --git a/FluidSimulation/FluidField.cs b/FluidSimulation/FluidField.cs index a4b01c9237..d9079427e5 100644 --- a/FluidSimulation/FluidField.cs +++ b/FluidSimulation/FluidField.cs @@ -96,14 +96,14 @@ namespace CalamityMod.FluidSimulation internal void ApplyThingToTarget(RenderTarget2D currentField, Action shaderPreparationsAction) { - Main.instance.GraphicsDevice.SetRenderTarget(TemporaryAuxilaryTarget); - Main.instance.GraphicsDevice.Clear(Color.Transparent); + using (TemporaryAuxilaryTarget.Scope(clearColor: Color.Transparent)) + { + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); - - shaderPreparationsAction(); - Main.spriteBatch.Draw(currentField, currentField.Bounds, Color.White); - Main.spriteBatch.End(); + shaderPreparationsAction(); + Main.spriteBatch.Draw(currentField, currentField.Bounds, Color.White); + Main.spriteBatch.End(); + } currentField.CopyContentsFrom(TemporaryAuxilaryTarget); } @@ -202,8 +202,7 @@ namespace CalamityMod.FluidSimulation }); // Clear the Poisson values and then calculate them, for use in the divergence clearance pass. - Main.instance.GraphicsDevice.SetRenderTarget(DivergencePoissonField); - Main.instance.GraphicsDevice.Clear(Color.Transparent); + using (DivergencePoissonField.Scope(clearColor: Color.Transparent)) { } for (int i = 0; i < GaussSeidelIterations; i++) { @@ -275,16 +274,14 @@ namespace CalamityMod.FluidSimulation public void UpdateOutputTarget() { - Main.instance.GraphicsDevice.SetRenderTarget(OutputTarget); - Main.instance.GraphicsDevice.Clear(Color.Transparent); - - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); - Main.instance.GraphicsDevice.Textures[5] = ColorField.NextState.Target; - CalamityShaders.FluidShaders.Value.CurrentTechnique.Passes["DrawFluidPass"].Apply(); - Main.spriteBatch.Draw(DensityField.NextState.Target, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, 1f, 0, 0f); - Main.spriteBatch.End(); - - Main.instance.GraphicsDevice.SetRenderTarget(null); + using (OutputTarget.Scope(clearColor: Color.Transparent)) + { + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); + Main.instance.GraphicsDevice.Textures[5] = ColorField.NextState.Target; + CalamityShaders.FluidShaders.Value.CurrentTechnique.Passes["DrawFluidPass"].Apply(); + Main.spriteBatch.Draw(DensityField.NextState.Target, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, 1f, 0, 0f); + Main.spriteBatch.End(); + } } public void Dispose() diff --git a/Graphics/Metaballs/MetaballManager.cs b/Graphics/Metaballs/MetaballManager.cs index 107f2dbeba..a051f064c8 100644 --- a/Graphics/Metaballs/MetaballManager.cs +++ b/Graphics/Metaballs/MetaballManager.cs @@ -2,6 +2,7 @@ using System.Linq; using CalamityMod.Enums; using CalamityMod.Systems.Graphic; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -72,18 +73,17 @@ namespace CalamityMod.Graphics.Metaballs // Draw the raw contents of the metaball to each of its render targets. foreach (var target in metaball.LayerTargets) { - gd.SetRenderTarget(target); - gd.Clear(Color.Transparent); - metaball.DrawInstances(); + using (target.Scope(clearColor: Color.Transparent)) + { + metaball.DrawInstances(); - // Flush metaball contents to its render target and reset the sprite batch for the next iteration. - Main.spriteBatch.End(); - Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, Main.Rasterizer, null, Main.Transform); + // Flush metaball contents to its render target and reset the sprite batch for the next iteration. + Main.spriteBatch.End(); + Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, Main.Rasterizer, null, Main.Transform); + } } } - // Return to the backbuffer and end the sprite batch. - gd.SetRenderTarget(null); Main.spriteBatch.End(); } diff --git a/Graphics/Renderers/RendererManager.cs b/Graphics/Renderers/RendererManager.cs index 9665bab61b..225e743a61 100644 --- a/Graphics/Renderers/RendererManager.cs +++ b/Graphics/Renderers/RendererManager.cs @@ -3,6 +3,7 @@ using System.Linq; using CalamityMod.Enums; using CalamityMod.Systems.Graphic; using CalamityMod.Utilities.Daybreak; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -93,9 +94,8 @@ namespace CalamityMod.Graphics.Renderers continue; using (Main.spriteBatch.Scope()) + using (renderer.MainTarget.Scope(clearColor: Color.Transparent)) { - Main.instance.GraphicsDevice.SetRenderTarget(renderer.MainTarget); - Main.instance.GraphicsDevice.Clear(Color.Transparent); Main.spriteBatch.Begin( SpriteSortMode.Deferred, BlendState.AlphaBlend, @@ -109,8 +109,6 @@ namespace CalamityMod.Graphics.Renderers Main.spriteBatch.End(); } } - - Main.instance.GraphicsDevice.SetRenderTarget(null); } #endregion } diff --git a/Systems/Graphic/LiquidSystem/ModLavaStyleSystem_RT.cs b/Systems/Graphic/LiquidSystem/ModLavaStyleSystem_RT.cs index 167bbece0d..4fdf3ee22e 100644 --- a/Systems/Graphic/LiquidSystem/ModLavaStyleSystem_RT.cs +++ b/Systems/Graphic/LiquidSystem/ModLavaStyleSystem_RT.cs @@ -1,4 +1,5 @@ -using Microsoft.Xna.Framework; +using CalamityMod.Utilities.Daybreak.Buffers; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; using Terraria; @@ -58,32 +59,33 @@ namespace CalamityMod.Systems.Graphic.LiquidSystem if (!Initialized || !TextureArrayReady || Main.gameMenu) return; - var graphicsDevice = Main.instance.GraphicsDevice; - graphicsDevice.SetRenderTarget(LavaRT); - graphicsDevice.Clear(Color.Transparent); - Begin(); - DrawTextures(Textures); - End(); + using (LavaRT.Scope(clearColor: Color.Transparent)) + { + Begin(); + DrawTextures(Textures); + End(); + } - graphicsDevice.SetRenderTarget(LavaBlockRT); - graphicsDevice.Clear(Color.Transparent); - Begin(); - DrawTextures(BlockTextures); - End(); + using (LavaBlockRT.Scope(clearColor: Color.Transparent)) + { + Begin(); + DrawTextures(BlockTextures); + End(); + } - graphicsDevice.SetRenderTarget(LavaSlopeRT); - graphicsDevice.Clear(Color.Transparent); - Begin(); - DrawTextures(SlopeTextures); - End(); + using (LavaSlopeRT.Scope(clearColor: Color.Transparent)) + { + Begin(); + DrawTextures(SlopeTextures); + End(); + } - graphicsDevice.SetRenderTarget(LavaWaterfallRT); - graphicsDevice.Clear(Color.Transparent); - Begin(); - DrawTextures(WaterfallTextures); - End(); - - graphicsDevice.SetRenderTarget(null); + using (LavaWaterfallRT.Scope(clearColor: Color.Transparent)) + { + Begin(); + DrawTextures(WaterfallTextures); + End(); + } } private static readonly BlendState ActualAdditive = new() diff --git a/Systems/TileMerging/TileBlendTexture_Baking.cs b/Systems/TileMerging/TileBlendTexture_Baking.cs index de51103d63..a40a39dc52 100644 --- a/Systems/TileMerging/TileBlendTexture_Baking.cs +++ b/Systems/TileMerging/TileBlendTexture_Baking.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -62,20 +63,17 @@ namespace CalamityMod.Systems var renderTarget = BakedBlendTexture; if (renderTarget != null && !renderTarget.IsDisposed && !renderTarget.IsContentLost) { - graphicsDevice.SetRenderTarget(renderTarget); - if (_ShouldClearRT) + using (renderTarget.Scope(clearColor: _ShouldClearRT ? Color.Transparent : null)) { - graphicsDevice.Clear(Color.Transparent); _ShouldClearRT = false; + + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullNone); + + BakeBlendTextureCache(v); + + Main.spriteBatch.End(); } - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullNone); - - BakeBlendTextureCache(v); - - Main.spriteBatch.End(); - graphicsDevice.SetRenderTarget(null); - _RequestedVariants[variant] = false; _IsBaked[variant] = true; } diff --git a/Utilities/DrawingUtils.cs b/Utilities/DrawingUtils.cs index 6941342c23..0fc90e184c 100644 --- a/Utilities/DrawingUtils.cs +++ b/Utilities/DrawingUtils.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; @@ -356,16 +357,14 @@ namespace CalamityMod ///
public static void CopyContentsFrom(this RenderTarget2D to, RenderTarget2D from) { - Main.instance.GraphicsDevice.SetRenderTarget(to); - Main.instance.GraphicsDevice.Clear(Color.Transparent); + using (to.Scope(clearColor: Color.Transparent)) + { + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); + Main.spriteBatch.Draw(from, Vector2.Zero, null, Color.White); + Main.spriteBatch.End(); + } - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); - Main.spriteBatch.Draw(from, Vector2.Zero, null, Color.White); - Main.spriteBatch.End(); - - Main.instance.GraphicsDevice.SetRenderTarget(from); - Main.instance.GraphicsDevice.Clear(Color.Transparent); - Main.instance.GraphicsDevice.SetRenderTarget(null); + using (from.Scope(clearColor: Color.Transparent)) { } } /// From 8e2b48a7d9e69113ece2792a21f947d15eb90c3c Mon Sep 17 00:00:00 2001 From: Stephen Thiebaud Date: Sat, 27 Dec 2025 03:53:06 -0600 Subject: [PATCH 16/53] fix: remove previously-unverified setrendertarget calls and restore code to a compilable state --- FluidSimulation/FluidField.cs | 22 ++++---- .../Primitives/PrimitivePixelationSystem.cs | 38 +++++++------ MainMenu/CalamityMainMenu_Sunken.cs | 54 +++++++++---------- Particles/DeathAshParticle.cs | 27 +++++----- .../PixelationSystem/PixelationManager.cs | 2 - 5 files changed, 69 insertions(+), 74 deletions(-) diff --git a/FluidSimulation/FluidField.cs b/FluidSimulation/FluidField.cs index d9079427e5..213307ced2 100644 --- a/FluidSimulation/FluidField.cs +++ b/FluidSimulation/FluidField.cs @@ -105,12 +105,12 @@ namespace CalamityMod.FluidSimulation Main.spriteBatch.End(); } - currentField.CopyContentsFrom(TemporaryAuxilaryTarget); + currentField.CopyContentsFrom(TemporaryAuxilaryTarget.Target); } internal void FlushQueueToTarget(FluidFieldState field) { - ApplyThingToTarget(field.NextState, () => + ApplyThingToTarget(field.NextState.Target, () => { int batchIndex = 0; int pixelCount = field.PendingChanges.Count; @@ -167,7 +167,7 @@ namespace CalamityMod.FluidSimulation internal void CalculateDiffusion(float diffusionFactor, FluidFieldState field, bool colors = false) { diffusionFactor *= DeltaTime * Size; - ApplyThingToTarget(field.NextState, () => + ApplyThingToTarget(field.NextState.Target, () => { Main.instance.GraphicsDevice.Textures[1] = field.PreviousState.Target; CalamityShaders.FluidShaders.Value.Parameters["size"].SetValue(Size); @@ -194,7 +194,7 @@ namespace CalamityMod.FluidSimulation internal void ClearDivergence(RenderTarget2D velocities) { // Calculate divergence. - ApplyThingToTarget(DivergenceField, () => + ApplyThingToTarget(DivergenceField.Target, () => { Main.instance.GraphicsDevice.Textures[2] = velocities; CalamityShaders.FluidShaders.Value.Parameters["size"].SetValue(Size); @@ -206,7 +206,7 @@ namespace CalamityMod.FluidSimulation for (int i = 0; i < GaussSeidelIterations; i++) { - ApplyThingToTarget(DivergencePoissonField, () => + ApplyThingToTarget(DivergencePoissonField.Target, () => { Main.instance.GraphicsDevice.Textures[1] = DivergencePoissonField.Target; Main.instance.GraphicsDevice.Textures[2] = velocities; @@ -254,22 +254,22 @@ namespace CalamityMod.FluidSimulation { CalculateDiffusion(Viscosity, VelocityField); if (!ShouldSkipDivergenceClearingStep) - ClearDivergence(VelocityField.NextState); + ClearDivergence(VelocityField.NextState.Target); - CalculateAdvection(VelocityField.NextState, VelocityField.PreviousState, VelocityField.PreviousState); + CalculateAdvection(VelocityField.NextState.Target, VelocityField.PreviousState.Target, VelocityField.PreviousState.Target); if (!ShouldSkipDivergenceClearingStep) - ClearDivergence(VelocityField.NextState); + ClearDivergence(VelocityField.NextState.Target); } internal void UpdateDensityFields() { CalculateDiffusion(DiffusionFactor, DensityField); DensityField.SwapState(); - CalculateAdvection(DensityField.PreviousState, DensityField.NextState, VelocityField.NextState); + CalculateAdvection(DensityField.PreviousState.Target, DensityField.NextState.Target, VelocityField.NextState.Target); CalculateDiffusion(DiffusionFactor, ColorField, true); ColorField.SwapState(); - CalculateAdvection(ColorField.PreviousState, ColorField.NextState, VelocityField.NextState, true); + CalculateAdvection(ColorField.PreviousState.Target, ColorField.NextState.Target, VelocityField.NextState.Target, true); } public void UpdateOutputTarget() @@ -318,7 +318,7 @@ namespace CalamityMod.FluidSimulation Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, drawPerspective); - shaderPreparations?.Invoke(OutputTarget); + shaderPreparations?.Invoke(OutputTarget.Target); Main.spriteBatch.Draw(OutputTarget.Target, drawPosition, null, Color.White, 0f, OutputTarget.Target.Size() * 0.5f, Scale, 0, 0f); Main.spriteBatch.End(); diff --git a/Graphics/Primitives/PrimitivePixelationSystem.cs b/Graphics/Primitives/PrimitivePixelationSystem.cs index 30b3b504cf..582591c4a0 100644 --- a/Graphics/Primitives/PrimitivePixelationSystem.cs +++ b/Graphics/Primitives/PrimitivePixelationSystem.cs @@ -155,17 +155,15 @@ namespace CalamityMod.Graphics.Primitives CurrentlyRendering = true; - DrawPrimsToRenderTarget(PixelationTarget_BeforeAllTiles, GeneralDrawLayer.BeforeAllTiles, beforeAllTiles); - DrawPrimsToRenderTarget(PixelationTarget_BeforeSolidTiles, GeneralDrawLayer.BeforeSolidTiles, beforeSolidTiles); - DrawPrimsToRenderTarget(PixelationTarget_BeforeNPCs, GeneralDrawLayer.BeforeNPCs, beforeNPCs); - DrawPrimsToRenderTarget(PixelationTarget_AfterNPCs, GeneralDrawLayer.AfterNPCs, afterNPCs); - DrawPrimsToRenderTarget(PixelationTarget_BeforeProjectiles, GeneralDrawLayer.BeforeProjectiles, beforeProjectiles); - DrawPrimsToRenderTarget(PixelationTarget_AfterProjectiles, GeneralDrawLayer.AfterProjectiles, afterProjectiles); - DrawPrimsToRenderTarget(PixelationTarget_AfterPlayers, GeneralDrawLayer.AfterPlayers, afterPlayers); - DrawPrimsToRenderTarget(PixelationTarget_AfterDusts, GeneralDrawLayer.AfterDusts, afterDusts); - DrawPrimsToRenderTarget(PixelationTarget_AfterEverything, GeneralDrawLayer.AfterEverything, afterEverything); - - Main.instance.GraphicsDevice.SetRenderTarget(null); + DrawPrimsToRenderTarget(PixelationTarget_BeforeAllTiles.Target, GeneralDrawLayer.BeforeAllTiles, beforeAllTiles); + DrawPrimsToRenderTarget(PixelationTarget_BeforeSolidTiles.Target, GeneralDrawLayer.BeforeSolidTiles, beforeSolidTiles); + DrawPrimsToRenderTarget(PixelationTarget_BeforeNPCs.Target, GeneralDrawLayer.BeforeNPCs, beforeNPCs); + DrawPrimsToRenderTarget(PixelationTarget_AfterNPCs.Target, GeneralDrawLayer.AfterNPCs, afterNPCs); + DrawPrimsToRenderTarget(PixelationTarget_BeforeProjectiles.Target, GeneralDrawLayer.BeforeProjectiles, beforeProjectiles); + DrawPrimsToRenderTarget(PixelationTarget_AfterProjectiles.Target, GeneralDrawLayer.AfterProjectiles, afterProjectiles); + DrawPrimsToRenderTarget(PixelationTarget_AfterPlayers.Target, GeneralDrawLayer.AfterPlayers, afterPlayers); + DrawPrimsToRenderTarget(PixelationTarget_AfterDusts.Target, GeneralDrawLayer.AfterDusts, afterDusts); + DrawPrimsToRenderTarget(PixelationTarget_AfterEverything.Target, GeneralDrawLayer.AfterEverything, afterEverything); CurrentlyRendering = false; } @@ -201,15 +199,15 @@ namespace CalamityMod.Graphics.Primitives { return drawLayer switch { - GeneralDrawLayer.BeforeAllTiles => PixelationTarget_BeforeAllTiles, - GeneralDrawLayer.BeforeSolidTiles => PixelationTarget_BeforeSolidTiles, - GeneralDrawLayer.BeforeNPCs => PixelationTarget_BeforeNPCs, - GeneralDrawLayer.AfterNPCs => PixelationTarget_AfterNPCs, - GeneralDrawLayer.BeforeProjectiles => PixelationTarget_BeforeProjectiles, - GeneralDrawLayer.AfterProjectiles => PixelationTarget_AfterProjectiles, - GeneralDrawLayer.AfterPlayers => PixelationTarget_AfterPlayers, - GeneralDrawLayer.AfterDusts => PixelationTarget_AfterDusts, - _ => PixelationTarget_AfterEverything + GeneralDrawLayer.BeforeAllTiles => PixelationTarget_BeforeAllTiles.Target, + GeneralDrawLayer.BeforeSolidTiles => PixelationTarget_BeforeSolidTiles.Target, + GeneralDrawLayer.BeforeNPCs => PixelationTarget_BeforeNPCs.Target, + GeneralDrawLayer.AfterNPCs => PixelationTarget_AfterNPCs.Target, + GeneralDrawLayer.BeforeProjectiles => PixelationTarget_BeforeProjectiles.Target, + GeneralDrawLayer.AfterProjectiles => PixelationTarget_AfterProjectiles.Target, + GeneralDrawLayer.AfterPlayers => PixelationTarget_AfterPlayers.Target, + GeneralDrawLayer.AfterDusts => PixelationTarget_AfterDusts.Target, + _ => PixelationTarget_AfterEverything.Target }; } #endregion diff --git a/MainMenu/CalamityMainMenu_Sunken.cs b/MainMenu/CalamityMainMenu_Sunken.cs index 244c34fba2..661e9c03f8 100644 --- a/MainMenu/CalamityMainMenu_Sunken.cs +++ b/MainMenu/CalamityMainMenu_Sunken.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using CalamityMod.Effects; using CalamityMod.Systems; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; @@ -170,40 +171,39 @@ namespace CalamityMod.MainMenu { sb.End(); - Main.instance.GraphicsDevice.SetRenderTarget(logoWaterFillTarget); - Main.instance.GraphicsDevice.Clear(Color.Transparent); + using (logoWaterFillTarget.Scope(clearColor: Color.Transparent)) + { + sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Matrix.Identity); - sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Matrix.Identity); + var fillShader = CalamityShaders.SunkenSeaMenuLogoWater.Value; + fillShader.Parameters["uImageSize"]?.SetValue(LogoWaterFill.Size()); + fillShader.Parameters["uTexture0"]?.SetValue(WorleyInverted.Value); + fillShader.Parameters["uBubbleTexture"]?.SetValue(Perlin.Value); + //fillShader.Parameters["uFillAmount"]?.SetValue(0.75f + (MathF.Sin(Main.GlobalTimeWrappedHourly) / 2f) * 0.25f); + fillShader.Parameters["uFillAmount"]?.SetValue(0.75f); + fillShader.Parameters["uWaveStrength"]?.SetValue(2.5f); + fillShader.Parameters["uWaveOffset"]?.SetValue(0.6f); + fillShader.Parameters["uSubtract"]?.SetValue(0.4f); + fillShader.Parameters["uTime"]?.SetValue(Main.GlobalTimeWrappedHourly); + fillShader.Parameters["uFillColor"]?.SetValue(new Color(67, 187, 204, 255 / 2).ToVector4() * 0.7f); + fillShader.Parameters["uEdgeColor"]?.SetValue(new Color(16, 99, 112, 255 / 2).ToVector4() * 0.7f); + fillShader.Parameters["uLineColor"]?.SetValue(new Color(179, 255, 255, 255 / 2).ToVector4() * 0.7f); + fillShader.CurrentTechnique.Passes[0].Apply(); - var fillShader = CalamityShaders.SunkenSeaMenuLogoWater.Value; - fillShader.Parameters["uImageSize"]?.SetValue(LogoWaterFill.Size()); - fillShader.Parameters["uTexture0"]?.SetValue(WorleyInverted.Value); - fillShader.Parameters["uBubbleTexture"]?.SetValue(Perlin.Value); - //fillShader.Parameters["uFillAmount"]?.SetValue(0.75f + (MathF.Sin(Main.GlobalTimeWrappedHourly) / 2f) * 0.25f); - fillShader.Parameters["uFillAmount"]?.SetValue(0.75f); - fillShader.Parameters["uWaveStrength"]?.SetValue(2.5f); - fillShader.Parameters["uWaveOffset"]?.SetValue(0.6f); - fillShader.Parameters["uSubtract"]?.SetValue(0.4f); - fillShader.Parameters["uTime"]?.SetValue(Main.GlobalTimeWrappedHourly); - fillShader.Parameters["uFillColor"]?.SetValue(new Color(67, 187, 204, 255 / 2).ToVector4() * 0.7f); - fillShader.Parameters["uEdgeColor"]?.SetValue(new Color(16, 99, 112, 255 / 2).ToVector4() * 0.7f); - fillShader.Parameters["uLineColor"]?.SetValue(new Color(179, 255, 255, 255 / 2).ToVector4() * 0.7f); - fillShader.CurrentTechnique.Passes[0].Apply(); + sb.Draw(LogoWaterFill.Value, Vector2.Zero, Color.White); - sb.Draw(LogoWaterFill.Value, Vector2.Zero, Color.White); - - sb.End(); + sb.End(); + } Main.pixelShader.CurrentTechnique.Passes[0].Apply(); - Main.instance.GraphicsDevice.SetRenderTarget(logoTarget); - Main.instance.GraphicsDevice.Clear(Color.Transparent); - sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Matrix.Identity); + using (logoTarget.Scope(clearColor: Color.Transparent)) + { + sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Matrix.Identity); + sb.Draw(logoWaterFillTarget, new Vector2(406, 48), Color.White); + sb.End(); + } - sb.Draw(logoWaterFillTarget, new Vector2(406, 48), Color.White); - - sb.End(); - Main.instance.GraphicsDevice.SetRenderTarget(null); sb.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Main.UIScaleMatrix); } diff --git a/Particles/DeathAshParticle.cs b/Particles/DeathAshParticle.cs index 899d77578b..98d0553b5d 100644 --- a/Particles/DeathAshParticle.cs +++ b/Particles/DeathAshParticle.cs @@ -66,23 +66,22 @@ namespace CalamityMod.Particles Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); // Draw the NPC to the temporary render target so that all of its drawcode is localized, and then get the colors from the results. - Main.instance.GraphicsDevice.SetRenderTarget(PendingNPCsToDraw[npc]); - Main.instance.GraphicsDevice.Clear(Color.Transparent); - - Vector2 oldPosition = npc.position; - npc.oldPos = new Vector2[npc.oldPos.Length]; - npc.position = Main.screenPosition + new Vector2(Main.screenWidth, Main.screenHeight) * 0.5f; - try + using (PendingNPCsToDraw[npc].Scope(clearColor: Color.Transparent)) { - Main.instance.DrawNPC(npc.whoAmI, true); - } - catch { } - npc.position = oldPosition; - npc.Opacity = 0f; + Vector2 oldPosition = npc.position; + npc.oldPos = new Vector2[npc.oldPos.Length]; + npc.position = Main.screenPosition + new Vector2(Main.screenWidth, Main.screenHeight) * 0.5f; + try + { + Main.instance.DrawNPC(npc.whoAmI, true); + } + catch { } + npc.position = oldPosition; + npc.Opacity = 0f; - Main.spriteBatch.End(); + Main.spriteBatch.End(); + } } - Main.instance.GraphicsDevice.SetRenderTarget(null); } public static void CreateAshesFromNPC(NPC npc, Vector2 velocityOverride) diff --git a/Systems/Graphic/PixelationSystem/PixelationManager.cs b/Systems/Graphic/PixelationSystem/PixelationManager.cs index eb31a01187..a1f47dea93 100644 --- a/Systems/Graphic/PixelationSystem/PixelationManager.cs +++ b/Systems/Graphic/PixelationSystem/PixelationManager.cs @@ -159,8 +159,6 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem DrawCollectionsToTarget(PixelTargets_AfterPlayers, PixelationMatrix, ActivePixelatedDrawers_AfterPlayers); DrawCollectionsToTarget(PixelTargets_AfterDusts, PixelationMatrix, ActivePixelatedDrawers_AfterDusts); DrawCollectionsToTarget(PixelTargets_AfterEverything, PixelationMatrix, ActivePixelatedDrawers_AfterEverything); - - Main.graphics.GraphicsDevice.SetRenderTarget(null); } } From 041a52e09624c9f3868890f46958f5818781ef64 Mon Sep 17 00:00:00 2001 From: Stephen Thiebaud Date: Sat, 27 Dec 2025 03:59:53 -0600 Subject: [PATCH 17/53] feat: deprecate baserenderer --- Graphics/Renderers/BaseRenderer.cs | 148 ++++++++++++++--------------- 1 file changed, 74 insertions(+), 74 deletions(-) diff --git a/Graphics/Renderers/BaseRenderer.cs b/Graphics/Renderers/BaseRenderer.cs index cfbe060ec6..99e1994015 100644 --- a/Graphics/Renderers/BaseRenderer.cs +++ b/Graphics/Renderers/BaseRenderer.cs @@ -6,83 +6,83 @@ using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.ModLoader; -namespace CalamityMod.Graphics.Renderers +namespace CalamityMod.Graphics.Renderers; + +/// +/// A class to handle drawing a visual effect to a rendertarget, then drawing the target to the screen at selected layer. +/// +[Obsolete("BaseRenderer is obsolete; developers should explore other avenues for rendering")] +public abstract class BaseRenderer : ModType { + #region Fields/Properties /// - /// A class to handle drawing a visual effect to a rendertarget, then drawing the target to the screen at selected layer. + /// The layer that the target should be drawn at. /// - public abstract class BaseRenderer : ModType + public abstract GeneralDrawLayer Layer { get; } + + /// + /// Whether the target should draw and be drawn to this frame. + /// + public abstract bool ShouldDraw { get; } + + /// + /// The target that the visual is drawn to. Automatically handled. + /// + public RenderTargetLease MainTarget { - #region Fields/Properties - /// - /// The layer that the target should be drawn at. - /// - public abstract GeneralDrawLayer Layer { get; } - - /// - /// Whether the target should draw and be drawn to this frame. - /// - public abstract bool ShouldDraw { get; } - - /// - /// The target that the visual is drawn to. Automatically handled. - /// - public RenderTargetLease MainTarget - { - get; - private set; - } - #endregion - - #region Methods - protected sealed override void Register() - { - ModTypeLookup.Register(this); - - if (RendererManager.Renderers.Contains(this)) - throw new Exception($"Renderer '{Name}' has already been registered!"); - - RendererManager.Renderers.Add(this); - } - - - public sealed override void SetupContent() => SetStaticDefaults(); - - public sealed override void SetStaticDefaults() - { - Main.QueueMainThreadAction(() => - { - MainTarget = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); - }); - } - - /// - /// Called from . - /// - public virtual void PreUpdate() - { - - } - - /// - /// Called from . - /// - public virtual void PostUpdate() - { - - } - - /// - /// Draw whatever needed to the target here. - /// - /// - public abstract void DrawToTarget(SpriteBatch spriteBatch); - - /// - /// Draw the target here. By default, just draws the target. - /// - /// - public virtual void DrawTarget(SpriteBatch spriteBatch) => spriteBatch.Draw(MainTarget.Target, Vector2.Zero, Color.White); - #endregion + get; + private set; } + #endregion + + #region Methods + protected sealed override void Register() + { + ModTypeLookup.Register(this); + + if (RendererManager.Renderers.Contains(this)) + throw new Exception($"Renderer '{Name}' has already been registered!"); + + RendererManager.Renderers.Add(this); + } + + + public sealed override void SetupContent() => SetStaticDefaults(); + + public sealed override void SetStaticDefaults() + { + Main.QueueMainThreadAction(() => + { + MainTarget = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); + }); + } + + /// + /// Called from . + /// + public virtual void PreUpdate() + { + + } + + /// + /// Called from . + /// + public virtual void PostUpdate() + { + + } + + /// + /// Draw whatever needed to the target here. + /// + /// + public abstract void DrawToTarget(SpriteBatch spriteBatch); + + /// + /// Draw the target here. By default, just draws the target. + /// + /// + public virtual void DrawTarget(SpriteBatch spriteBatch) => spriteBatch.Draw(MainTarget.Target, Vector2.Zero, Color.White); + #endregion } From 0bf1babdcffc17a40a436226be677fb97a0949ea Mon Sep 17 00:00:00 2001 From: Big E Date: Sun, 28 Dec 2025 22:16:53 -0500 Subject: [PATCH 18/53] + Suggested Brain of Cthulhu Balance Changes --- .../Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs | 1 + .../VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs index 39dd8f8055..fca976e5b0 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs @@ -271,6 +271,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride public override void SetDefaults(Mod mod) { + NPC.damage = NPC.defDamage = 64; BoCDrawOffset = Vector2.Zero; ShieldOpacity = 1f; ShieldScale = 1f; diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs index 29f9af959b..f91c657bb0 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs @@ -67,6 +67,11 @@ public class CreeperAI : VanillaAIOverride public override bool EnableMultiplayerSmoothingAheadOfAI => true; + public override void SetDefaults(Mod mod) + { + NPC.damage = NPC.defDamage = 64; + } + public override bool AI(Mod mod) { #region Despawn From 399d0a20da7ed728672fafacc1833137a6cfd747 Mon Sep 17 00:00:00 2001 From: CongratsIsTrash <1q2w3e4dasd@gmail.com> Date: Sun, 28 Dec 2025 23:55:02 -0500 Subject: [PATCH 19/53] Corrected damage values --- .../Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs | 2 +- NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs index fca976e5b0..5b313b1f8d 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs @@ -271,7 +271,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride public override void SetDefaults(Mod mod) { - NPC.damage = NPC.defDamage = 64; + NPC.damage = NPC.defDamage = 36; BoCDrawOffset = Vector2.Zero; ShieldOpacity = 1f; ShieldScale = 1f; diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs index f91c657bb0..4fc2e05152 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs @@ -69,7 +69,7 @@ public class CreeperAI : VanillaAIOverride public override void SetDefaults(Mod mod) { - NPC.damage = NPC.defDamage = 64; + NPC.damage = NPC.defDamage = 36; } public override bool AI(Mod mod) From bb8fc29adb8e7182f1d5337289957cff1a8c11d3 Mon Sep 17 00:00:00 2001 From: CongratsIsTrash <1q2w3e4dasd@gmail.com> Date: Mon, 29 Dec 2025 00:31:46 -0500 Subject: [PATCH 20/53] Comments on damage scaling --- .../Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs | 2 +- NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs index 5b313b1f8d..dd315cab0b 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs @@ -271,7 +271,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride public override void SetDefaults(Mod mod) { - NPC.damage = NPC.defDamage = 36; + NPC.damage = NPC.defDamage = 36; // 64 (1.8x expert scaling) BoCDrawOffset = Vector2.Zero; ShieldOpacity = 1f; ShieldScale = 1f; diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs index 4fc2e05152..f3b605ad05 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs @@ -69,7 +69,7 @@ public class CreeperAI : VanillaAIOverride public override void SetDefaults(Mod mod) { - NPC.damage = NPC.defDamage = 36; + NPC.damage = NPC.defDamage = 36; // 64 (1.8x expert scaling) } public override bool AI(Mod mod) From 762edab723b7cd05c0065cc6071542274772fbeb Mon Sep 17 00:00:00 2001 From: Nathanael Overton Date: Mon, 29 Dec 2025 01:14:50 -0500 Subject: [PATCH 21/53] Forgiveness (Painting) --- .../Paintings/ForgivenessPainting.cs | 19 ++++++++++ .../Paintings/ForgivenessPainting.png | Bin 0 -> 775 bytes .../Mods.CalamityMod.Items.Placeables.hjson | 5 +++ NPCs/CalamityGlobalTownNPC.cs | 1 + .../Paintings/ForgivenessPaintingTile.cs | 34 ++++++++++++++++++ .../Paintings/ForgivenessPaintingTile.png | Bin 0 -> 2526 bytes 6 files changed, 59 insertions(+) create mode 100644 Items/Placeables/Furniture/Paintings/ForgivenessPainting.cs create mode 100644 Items/Placeables/Furniture/Paintings/ForgivenessPainting.png create mode 100644 Tiles/Furniture/Paintings/ForgivenessPaintingTile.cs create mode 100644 Tiles/Furniture/Paintings/ForgivenessPaintingTile.png diff --git a/Items/Placeables/Furniture/Paintings/ForgivenessPainting.cs b/Items/Placeables/Furniture/Paintings/ForgivenessPainting.cs new file mode 100644 index 0000000000..1d6c192d94 --- /dev/null +++ b/Items/Placeables/Furniture/Paintings/ForgivenessPainting.cs @@ -0,0 +1,19 @@ +using CalamityMod.Tiles.Furniture.Paintings; +using Terraria; +using Terraria.ModLoader; + +namespace CalamityMod.Items.Placeables.Furniture.Paintings +{ + public class ForgivenessPainting : ModItem, ILocalizedModType + { + public new string LocalizationCategory => "Items.Placeables"; + + public override void SetDefaults() + { + Item.DefaultToPlaceableTile(ModContent.TileType()); + Item.width = 32; + Item.height = 32; + Item.value = Item.buyPrice(gold: 15); + } + } +} diff --git a/Items/Placeables/Furniture/Paintings/ForgivenessPainting.png b/Items/Placeables/Furniture/Paintings/ForgivenessPainting.png new file mode 100644 index 0000000000000000000000000000000000000000..a8627f069b702587196885c21f28af380ea8a2a3 GIT binary patch literal 775 zcmV+i1Ni)jP)Px#1ZP1_K>z@;j|==^1poj7u}MThR9HvN*Ih`HQ5**FV;|0-s0d}dFlkN~(IRlw za(ytHjS(c94BQZBhB2eNNTnb$rfJ~38I>2wx{1gLWz{f5v2qy>#1y|*7a_^Qh%8c< zEO`F!33^MqDLv1{ey>At@AIDjIWvh#Ii0CWNS7;;+tK&<+iURCDkf>)`c&L`dv_k* z*ru_-|CQOP4p?C7g5osr;#~vY2!%S~jqxHVkD|8;*7>eLd77>_LaW^YcWSo7=x{T% zTFvlKdKDC}0q?*bxL2DA59UCkLRQ*4#jJLPr=Q(3vjsx z>b2R@6{WajEgby3AEu_JL5I@`Yc6^rZ^D@V2#Pla%QawDZGb$XPMVTN`ze@LUI71= zG_@8w4G}0z1M4Jz%c$!bj9)qed8TTg!GauW;MGt++@<^Tn&DHSKYSF*BVGfFn)|S< z$_Ux_B~psctb$u})Nsr*4!io=q0+D$&h!n#mhb}@JYEcq!Cc5A?i5taPs5gmUdUsU z8sOngRC-!q$``tG9(D2}Y)jCcx6w8r@D%VhK=;E~q4^uk(kr1QLk~?AL1@D(V+YO* zz&Sq(Wt+~?m#slxGOXM|YlSh|4|v3DVC*e@(usu>SZJob{j23X^w-iF$*QJCVhLIU z56d^heD(v5^Uz_Sh8UyMGJlDl{hLKv^<5H-)s)r4-eLd%002ovPDHLk FV1h)RZK(hN literal 0 HcmV?d00001 diff --git a/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson b/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson index 8dff78f9bc..1e99ccea8f 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson @@ -913,6 +913,11 @@ CalamityCanvas2024: { ''' } +ForgivenessPainting: { + DisplayName: Forgiveness + Tooltip: D. User +} + ThankYouPainting: { DisplayName: Thank You Tooltip: diff --git a/NPCs/CalamityGlobalTownNPC.cs b/NPCs/CalamityGlobalTownNPC.cs index b7d9a200e4..469bf84c6a 100644 --- a/NPCs/CalamityGlobalTownNPC.cs +++ b/NPCs/CalamityGlobalTownNPC.cs @@ -1347,6 +1347,7 @@ namespace CalamityMod.NPCs .InsertAfter(ItemID.MusicBoxCredits, interlude3Box.Type, CalamityConditions.DownedYharon) .InsertAfter(ItemID.MusicBoxCredits, eulogyBox.Type, CalamityConditions.DownedDevourerOfGods) .AddWithCustomValue(ItemID.PrincessWeapon, Item.buyPrice(platinum: 1), Condition.Hardmode) + .AddWithCustomValue(ItemType(), Item.buyPrice(gold: 15), Condition.NpcIsPresent(NPCType())) .Add(); } diff --git a/Tiles/Furniture/Paintings/ForgivenessPaintingTile.cs b/Tiles/Furniture/Paintings/ForgivenessPaintingTile.cs new file mode 100644 index 0000000000..d19fa17fb2 --- /dev/null +++ b/Tiles/Furniture/Paintings/ForgivenessPaintingTile.cs @@ -0,0 +1,34 @@ +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.DataStructures; +using Terraria.ID; +using Terraria.Localization; +using Terraria.ModLoader; +using Terraria.ObjectData; + +namespace CalamityMod.Tiles.Furniture.Paintings +{ + public class ForgivenessPaintingTile : ModTile + { + public override void SetStaticDefaults() + { + Main.tileFrameImportant[Type] = true; + Main.tileLavaDeath[Type] = true; + Main.tileSpelunker[Type] = true; + Main.tileWaterDeath[Type] = false; + TileObjectData.newTile.CopyFrom(TileObjectData.Style3x3Wall); + TileObjectData.newTile.Width = 4; + TileObjectData.newTile.Height = 4; + TileObjectData.newTile.Origin = new Point16(2, 2); + TileObjectData.newTile.CoordinateHeights = new int[] { 16, 16, 16, 16 }; + TileObjectData.newTile.LavaDeath = true; + TileObjectData.addTile(Type); + + TileID.Sets.DisableSmartCursor[Type] = true; + TileID.Sets.FramesOnKillWall[Type] = true; + TileID.Sets.DisableSmartCursor[Type] = true; + DustType = DustID.WoodFurniture; + AddMapEntry(new Color(99, 50, 30), Language.GetText("MapObject.Painting")); + } + } +} diff --git a/Tiles/Furniture/Paintings/ForgivenessPaintingTile.png b/Tiles/Furniture/Paintings/ForgivenessPaintingTile.png new file mode 100644 index 0000000000000000000000000000000000000000..b4bee1eaa72e29fc08bca77608086b7053f24715 GIT binary patch literal 2526 zcmV<42_g20P)Px#1ZP1_K>z@;j|==^1pojEh)G02RCr$Pn}1YSv!N>b0J*WP-uXFDAeec(MALRSIzn{ef{_IC( zMkB}Gg>h;scl(u1=m1_%+{P(*wGi4jHW_-fu?_mWL~-<;Ll#0k#~5%v7&|NVw1&A9 z?3vbQyDPN~&DaQ!SLFN}o1JCsO+U|#M}C-y?fqvLV7ocwYHW5L!&=71bBqBeE1mze zB*u`KfqkK+EvKRSG4c02J$vvwPdNLGLCh-KH@^;TJ@Faz#QuLkbN2rnx_0jyP{MKe z^Yr8J(UH&{)8n8|s2EE;#~5(^VC)(1I_vr|@%KE!*icthgN@iuu{XvLJNwvM&71qM zk>GJ7eKwxw27hjJ^jK^rJjZx=Tozm_U$<<-%J0EPRocT}v1miG{=-G+nBuiG~@9*_vTGky%6y=*0v$0L)Uf}Xx36zazDz-drAV9eMt&?EoyjSbbOqM*k&it}_wu}^d3 z%|oDsPH8#%Z>R~+F$Rn=#?2{o1j%2!2AYyO2g>7#lO{tmGc%xBS<9d@ni)DkcM8!R z(%SkTwdc#w!NE}7DU5L=U*H-mPpRNJ#(?9Pih7CimVCfQr|@_^Uc2*PlJDIGI_2F4 z>5vg-BW5eYnWrPz-Dk|ukBROe9Xf?|jop*6Nu4kYYI&<`|L{A;e30~D z;W@^DT#)iOBML=q}}u$jA_AP>MJxw5kyrG+N%DiPz5aZjzXk zP%QP26LVM*E8Lu-ubuSR#kCn7!!;7&?@v6(7%*lfolmqG*WvrDZ%yYB{rt{g1H$`F zfY$Bb3+0N&SyL%=N9b!V_JA2n`V|yGAIm=p{pHBH&{5+DLM!U`K#AuV50A@&)4|Jl zc?#aB3YKU+f0FNadgbKBP(3>hnwfx(**`N^U>wE{#w4P@ug4&LoacVO%NDEdV~I67 zdd!)W@IC0$^A}*8*Eg=iIQ40ZY_Z-vC$VdK#4zZ?cZibSNq>cU9XuCY>ljwPGh-xr z6WtN4WLcl^nDBi!=kWL!c(t7)O6QCUxDIN)>sz_rn=AbpLZ^%vd;`=vDxy23dY}A1 zV;6f*RQZMD80Sfc_e2OQ-|;H8aHe%fw6|A7i)4vpCB}%;NFmQx8hMlayQ#0IkDr{* z4$fJn!e_rlDCxHL(V5Xp9QXYV5G(VRFevL79nUcajH_!M-6>@+#Y3&zb0A4mM?k~I z$kULPMHR{tzYExcd!=Yc) z$#taUh|~%7>bmrFIX_!H^+}kOB9t?$b7f6Lr^LT4{hzJ(&W7HaD^H7#3MhwGo^6Fz zcbtM+mSi#Uv)MUg8l*cwJjWPt9K$E7jy6i)qcq$%tI#QA!?r_ePpCg2>tKoXmem&f zwAvGnFIxcRbxV}POfYNhY`6-#x=muma^)1l`s<)_lqC;gI$10+R_;sX$NN^$pHC4_ zEQ(|2&g;kcg)znyjZcBzGUyC6e~DC zQ`s zONWs8AIMth!v=Ab9z#;LibD!Zq!+w6R-9AaA!{M7xk3WOS(f&Qv*#EOkIO>0XYig$ zl-RPaR{lD}DldT4{!RKA%sz}M7609Y#mc$-T#U1H`8Bp!+gf%)3!apF%C8m5li0V7 zkSCp(bsB0U#v~N4#5h^wp20Xf8@AhG-T#Edq`C9hp%EBc_WnpJ>>W*#t=6<1#yHOg z4Z%2itYNkyteja7c^y0#x@DyY2Fc7eXYh`WgzF9awm|6=_D(DIL#*bCK&*Ezheq{A6b%Y7b7xOQ?nbOxBM=$!uZygKHRa9v#wjcSK3jS}a~ zQO+Ql$}uGVr~PE-MX7VLnk3eYP?yb0l*LTYXt}4&N>^w2>Ca_HwN>0Wznb=ij$$2S zSyUo@oD<12v^~} zp4sV8dmrezHmMu{~*Tk7dq(A4f0f{$uZ8IM+1x#yemM*aGb7jQN-uTJ+%N6(JV21v;Q`R_NmalpoepAx(rQ-J-V*sD74V}|d oOn;fyQ@$?a@OsZN7sRsu4+No1lN91fEC2ui07*qoM6N<$f*B(W(f|Me literal 0 HcmV?d00001 From 2063645440f2f87ff5c9d654ceb5552d14f4b29e Mon Sep 17 00:00:00 2001 From: CongratsIsTrash <1q2w3e4dasd@gmail.com> Date: Mon, 29 Dec 2025 11:37:25 -0500 Subject: [PATCH 22/53] Added apostrophes to tooltip --- Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson b/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson index 1e99ccea8f..8748849c61 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson @@ -915,7 +915,7 @@ CalamityCanvas2024: { ForgivenessPainting: { DisplayName: Forgiveness - Tooltip: D. User + Tooltip: "'D. User'" } ThankYouPainting: { From ce57ad60733151aba1b79be46883a3680f90089e Mon Sep 17 00:00:00 2001 From: CongratsIsTrash <1q2w3e4dasd@gmail.com> Date: Mon, 29 Dec 2025 14:56:44 -0500 Subject: [PATCH 23/53] Re-reworked Lunar Wing effects All related to flight now Solar restores a chunk of flight time when a charge on the solar shield is consumed Vortex gradually restores flight time during Vortex stealth Nebula massively increases nebula booster pickup range while hovering Stardust gives scaling stardust guardian damage boost based on flight time used, along with increased range --- CalPlayer/CalamityPlayer.cs | 5 +-- CalPlayer/CalamityPlayerDashEffects.cs | 3 -- CalPlayer/CalamityPlayerMiscEffects.cs | 13 +++--- ILEditing/BalancingILChanges.cs | 41 ++++++------------- ILEditing/ILChangesLoading.cs | 2 +- Items/CalamityGlobalItem.cs | 6 +-- .../Mods.CalamityMod.Vanilla.Wings.hjson | 12 ++++-- Projectiles/CalamityGlobalProjectile.cs | 4 +- 8 files changed, 35 insertions(+), 51 deletions(-) diff --git a/CalPlayer/CalamityPlayer.cs b/CalPlayer/CalamityPlayer.cs index 142cecced2..72af7be190 100644 --- a/CalPlayer/CalamityPlayer.cs +++ b/CalPlayer/CalamityPlayer.cs @@ -957,8 +957,6 @@ namespace CalamityMod.CalPlayer public int PurityHealSlowdownFrames = 0; public bool harpyRing = false; public bool angelTreads = false; - /// Counter variable used for automatically re-engaging Vortex armor's stealth with Vortex Booster. - public int vortexBoosterStealthDelay = 0; /// Makes Flesh Knuckles and its upgrades increase the player's max health. public bool fleshKnuckles = false; public bool ironBoots = false; @@ -3380,7 +3378,6 @@ namespace CalamityMod.CalPlayer persecutedEnchantSummonTimer = 0; momentumCapacitorTime = 0; momentumCapacitorBoost = 0f; - vortexBoosterStealthDelay = 0; LungingDown = false; chaliceBleedoutBuffer = 0D; @@ -4468,6 +4465,7 @@ namespace CalamityMod.CalPlayer } #endregion + #region OnExtraJumpStarted public override void OnExtraJumpStarted(ExtraJump jump, ref bool playSound) { if (rainSet && Player.whoAmI == Main.myPlayer) @@ -4475,6 +4473,7 @@ namespace CalamityMod.CalPlayer RainArmorSetChange.SpawnRainArmorJump(Player); } } + #endregion #region PreUpdateMovement public override void PreUpdateMovement() diff --git a/CalPlayer/CalamityPlayerDashEffects.cs b/CalPlayer/CalamityPlayerDashEffects.cs index a28bf6750e..865f7c97e3 100644 --- a/CalPlayer/CalamityPlayerDashEffects.cs +++ b/CalPlayer/CalamityPlayerDashEffects.cs @@ -158,9 +158,6 @@ namespace CalamityMod.CalPlayer if (HasCustomDash) { - // Vortex Booster automatically re-engages Vortex armor's stealth after a delay when dashing - if (Player.wingsLogic == (int)VanillaWingID.WingsVortex && Player.vortexStealthActive) - vortexBoosterStealthDelay = 60; Player.vortexStealthActive = false; // Decide the player's facing direction. diff --git a/CalPlayer/CalamityPlayerMiscEffects.cs b/CalPlayer/CalamityPlayerMiscEffects.cs index 0c4c60e88f..f532ed248c 100644 --- a/CalPlayer/CalamityPlayerMiscEffects.cs +++ b/CalPlayer/CalamityPlayerMiscEffects.cs @@ -388,6 +388,13 @@ namespace CalamityMod.CalPlayer Lighting.AddLight(Player.Center, Color.MediumOrchid.ToVector3()); } + // Restore flight time during Vortex stealth with Vortex Booster + if (Player.vortexStealthActive && Player.wingsLogic == (int)VanillaWingID.WingsVortex) + { + if (Player.wingTime > 0 && Player.miscCounter % 3 == 0) + Player.wingTime++; + } + if (Player.HeldItem.type == ModContent.ItemType() && darklightEnergy > 0) { if (darklightEnergy == Lucrecia.MaxEnergy && !darklightEnergyPaused) @@ -2317,12 +2324,6 @@ namespace CalamityMod.CalPlayer hurtSoundTimer--; if (wingProjectileCooldown > 0) wingProjectileCooldown--; - if (vortexBoosterStealthDelay > 0) - { - vortexBoosterStealthDelay--; - if (vortexBoosterStealthDelay == 1 && Player.setVortex) - Player.vortexStealthActive = true; - } if (hallowedRuneCooldown > 0) hallowedRuneCooldown--; if (sulphurBubbleCooldown > 0) diff --git a/ILEditing/BalancingILChanges.cs b/ILEditing/BalancingILChanges.cs index 326f96bd78..8807cc2714 100644 --- a/ILEditing/BalancingILChanges.cs +++ b/ILEditing/BalancingILChanges.cs @@ -497,7 +497,7 @@ namespace CalamityMod.ILEditing } #endregion - #region SoC Buffs & Vortex Booster Keeping Stealth + #region Shield of Cthulhu Buffs private static void DashMovementEdits(On_Player.orig_DashMovement orig, Player self) { //This is a modified version of Vanilla's Shield of Cthulhu dash collision checks @@ -562,16 +562,7 @@ namespace CalamityMod.ILEditing } } } - - // Allows for Vortex Booster to automatically re-engage Vortex armor's stealth after a delay when dashing - bool vortexStealth = self.vortexStealthActive; orig(self); - - if (self.wingsLogic == (int)VanillaWingID.WingsVortex) - { - if (vortexStealth && !self.vortexStealthActive) - self.Calamity().vortexBoosterStealthDelay = 60; - } } #endregion @@ -601,9 +592,9 @@ namespace CalamityMod.ILEditing cursor.Emit(OpCodes.Ldc_I4, (int)VanillaWingID.WingsStardust); cursor.Emit(OpCodes.Bne_Un, label); - cursor.Emit(OpCodes.Ldc_R4, 900f); + cursor.Emit(OpCodes.Ldc_R4, 960f); cursor.Emit(OpCodes.Stloc, 4); - cursor.Emit(OpCodes.Ldc_R4, 900f); + cursor.Emit(OpCodes.Ldc_R4, 960f); cursor.Emit(OpCodes.Stloc, 5); cursor.MarkLabel(label); @@ -623,26 +614,18 @@ namespace CalamityMod.ILEditing } #endregion - #region Solar Wings Change to Solar Flare Armor Dash - private static void SolarWingsDashChange(ILContext il) + #region Solar Wings Change to Solar Flare Armor + private static bool SolarWingsDashChange(On_Player.orig_ConsumeSolarFlare orig, Player self) { - // Make Solar Wings always allow using Solar Flare armor's dash. - var cursor = new ILCursor(il); - - // Genuinely how the fuck is this the only OR opcode in the entire method - if (!cursor.TryGotoNext(MoveType.After, i => i.MatchOr())) + // Solar Wings restore flight time when Solar Flare armor's shield explodes + // This can trigger from either ramming enemies or taking damage + if (orig(self)) { - LogFailure("Solar Dash Change", "Could not locate the OR opcode."); - return; + if (self.wingsLogic == (int)VanillaWingID.WingsSolar) + self.wingTime += 60; + return true; } - - // Add an additional check for if the player is wearing Solar Wings. - cursor.Emit(OpCodes.Ldarg_0); - cursor.Emit(OpCodes.Ldfld, typeof(Player).GetField("wingsLogic")); - cursor.Emit(OpCodes.Ldc_I4, (int)VanillaWingID.WingsSolar); - cursor.EmitCeq(); - // Then OR it. - cursor.EmitOr(); + return false; } #endregion diff --git a/ILEditing/ILChangesLoading.cs b/ILEditing/ILChangesLoading.cs index 097e80ec90..49741c87c6 100644 --- a/ILEditing/ILChangesLoading.cs +++ b/ILEditing/ILChangesLoading.cs @@ -108,7 +108,7 @@ namespace CalamityMod.ILEditing IL_Projectile.Damage += VanillaBossResistChanges; IL_Projectile.AI_099_2 += LimitTerrarianProjectiles; IL_Projectile.AI_120_StardustGuardian += StardustGuardianAttackBuffs; - IL_Player.UpdateArmorSets += SolarWingsDashChange; + On_Player.ConsumeSolarFlare += SolarWingsDashChange; IL_Player.UpdateBuffs += UpdateBuffsBalancingChanges; IL_Player.ApplyVanillaHurtEffectModifiers += RemoveBeetleAndSolarFlareMultiplicativeDR; diff --git a/Items/CalamityGlobalItem.cs b/Items/CalamityGlobalItem.cs index 5c4aa7d112..0b561a8924 100644 --- a/Items/CalamityGlobalItem.cs +++ b/Items/CalamityGlobalItem.cs @@ -1467,9 +1467,9 @@ namespace CalamityMod.Items if (player.Calamity().victideSnailSet) grabRange += VictideHeadSnail.SetBonusGrabRangeBoost; - // Nebula boosters have greater pickup range while using Nebula Mantle. - if (player.wingsLogic == (int)VanillaWingID.WingsNebula && ItemID.Sets.NebulaPickup[item.type]) - grabRange *= 2; + // Nebula boosters have greater pickup range while hovering with Nebula Mantle. + if (player.wingsLogic == (int)VanillaWingID.WingsNebula && player.wingTime > 0f && player.controlJump && player.TryingToHoverDown && ItemID.Sets.NebulaPickup[item.type]) + grabRange *= 3; } #endregion diff --git a/Localization/en-US/Mods.CalamityMod.Vanilla.Wings.hjson b/Localization/en-US/Mods.CalamityMod.Vanilla.Wings.hjson index 40f7b60eda..2a9963a8f4 100644 --- a/Localization/en-US/Mods.CalamityMod.Vanilla.Wings.hjson +++ b/Localization/en-US/Mods.CalamityMod.Vanilla.Wings.hjson @@ -4,7 +4,11 @@ DemonWings: Increases fall speed FestiveWings: Spawns ornaments which restore flight time FinWings: Allows quick travel in water TatteredFairyWings: Leaves a trail of flight draining fairy dust -WingsNebula: Increases the pickup range of Nebula armor's nebula boosters -WingsSolar: Allows Solar Flare armor's dash to be used without any charges -WingsStardust: Greatly increases Stardust armor's stardust guardian damage and attack range -WingsVortex: Vortex armor's stealth ability is automatically reactivated 1 second after dashing +WingsNebula: Greatly increases the pickup range of Nebula armor's nebula boosters while hovering +WingsSolar: Solar Flare armor's shield restores flight time whenever a charge is consumed +WingsStardust: + ''' + Greatly increases Stardust armor's stardust guardian attack range + Stardust guardian damage increases the lower your flight time + ''' +WingsVortex: Vortex armor's stealth gradually restores flight time while activated diff --git a/Projectiles/CalamityGlobalProjectile.cs b/Projectiles/CalamityGlobalProjectile.cs index a390a77aff..0f93615a28 100644 --- a/Projectiles/CalamityGlobalProjectile.cs +++ b/Projectiles/CalamityGlobalProjectile.cs @@ -4547,8 +4547,8 @@ namespace CalamityMod.Projectiles } // Stardust Wings buff the Stardust Guardian's damage - if (player.wingsLogic == (int)VanillaWingID.WingsStardust && projectile.type == ProjectileID.StardustGuardian) - modifiers.SourceDamage *= 2f; + if (player.wingsLogic == (int)VanillaWingID.WingsStardust && player.wingTime > 0f && projectile.type == ProjectileID.StardustGuardian) + modifiers.SourceDamage *= MathF.Max(1f, MathHelper.Lerp(4f, 1f, player.wingTime / (float)player.wingTimeMax)); // If applicable, use ricoshot bonus damage if (totalRicoshotDamageBonus > 0f) From b30acba14a3ac4cd7ffc608791d91eea4e01fbbe Mon Sep 17 00:00:00 2001 From: Big E Date: Fri, 26 Dec 2025 03:37:35 -0500 Subject: [PATCH 24/53] + Added proper multiplayer support to Dialogue Display System --- CalamityNetcode.cs | 4 +- Packets/StartDialogueDisplayPacket.cs | 125 ++++++++++++++++++++++++ UI/DialogueDisplay/DialogueDisplayUI.cs | 97 ++++++++++++++++-- 3 files changed, 217 insertions(+), 9 deletions(-) create mode 100644 Packets/StartDialogueDisplayPacket.cs diff --git a/CalamityNetcode.cs b/CalamityNetcode.cs index bfffa1013f..33c5e2f016 100644 --- a/CalamityNetcode.cs +++ b/CalamityNetcode.cs @@ -209,6 +209,8 @@ namespace CalamityMod WantToRefundReforges, // Player Draw Effect Parameters - SyncPlayerDrawParameter + SyncPlayerDrawParameter, + + DialogueDisplayStart, } } diff --git a/Packets/StartDialogueDisplayPacket.cs b/Packets/StartDialogueDisplayPacket.cs new file mode 100644 index 0000000000..0cc1812a65 --- /dev/null +++ b/Packets/StartDialogueDisplayPacket.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Items.Weapons.Ranged; +using CalamityMod.Systems; +using CalamityMod.UI.DialogueDisplay.DisplayEffects; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader.IO; +using Terraria.Net; +using static CalamityMod.UI.DialogueDisplay.DialogueDisplaySystem; + +namespace CalamityMod.Packets +{ + internal sealed class StartDialogueDisplayPacket : CalamityPacket + { + public static StartDialogueDisplayPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.DialogueDisplayStart; + + public static void Send(string name, bool progressDialogue, Vector2 position, int index, int uptime, DisplayEffectID effect, float wrapWidth, int toClient = -1, int ignoreClient = -1) + { + // Only Server should send Reponse to Clients + if (!Main.dedServ) + return; + + var packet = Instance.CreateBasePacket(); + + packet.Write(name); + packet.WriteFlags(progressDialogue, false); + packet.WritePackedVector2(position); + packet.Write(index); + packet.Write(uptime); + packet.Write((byte)effect); + packet.Write(wrapWidth); + + packet.Send(toClient, ignoreClient); + } + + public enum EntityType + { + NPC, + Player, + Projectile + } + + public static void Send(string name, bool progressDialogue, EntityType type, int entity, int index, int uptime, DisplayEffectID effect, float wrapWidth, int toClient = -1, int ignoreClient = -1) + { + // Only Server should send Reponse to Clients + if (!Main.dedServ) + return; + + var packet = Instance.CreateBasePacket(); + + packet.Write(name); + packet.WriteFlags(progressDialogue, true); + packet.WriteFlags(type == EntityType.NPC, type == EntityType.Player); + packet.Write(entity); + packet.Write(index); + packet.Write(uptime); + packet.Write((byte)effect); + packet.Write(wrapWidth); + + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + // Only receive info as clients + if (Main.netMode != NetmodeID.MultiplayerClient) + { + packet.ReadString(); + packet.ReadFlags(out _, out bool n); + + if (n) + { + packet.ReadFlags(out _, out _); + packet.ReadInt32(); + } + else + packet.ReadPackedVector2(); + + packet.ReadInt32(); + packet.ReadInt32(); + packet.ReadByte(); + packet.ReadSingle(); + return; + } + + string name = packet.ReadString(); + packet.ReadFlags(out bool progressDialogue, out bool hasEntity); + + int entity = -1; + Vector2 pos = Vector2.zeroVector; + bool isNpc = false; + bool isPlayer = false; + if (hasEntity) + { + packet.ReadFlags(out isNpc, out isPlayer); + entity = packet.ReadInt32(); + } + else + pos = packet.ReadPackedVector2(); + + int index = packet.ReadInt32(); + int uptime = packet.ReadInt32(); + byte effect = packet.ReadByte(); + float wrapWidth = packet.ReadSingle(); + + DisplayEffect de = GetEffect((DisplayEffectID)effect); + + if (hasEntity) + StartDialogueOnClient(name, isNpc ? Main.npc[entity] : isPlayer ? Main.player[entity] : Main.projectile.FirstOrDefault(p => p.identity == entity), index, uptime, progressDialogue, de, wrapWidth); + else + StartDialogueOnClient(name, pos, index, uptime, progressDialogue, de, wrapWidth); + + } + } + +} diff --git a/UI/DialogueDisplay/DialogueDisplayUI.cs b/UI/DialogueDisplay/DialogueDisplayUI.cs index 4bf1265e07..18eb13319e 100644 --- a/UI/DialogueDisplay/DialogueDisplayUI.cs +++ b/UI/DialogueDisplay/DialogueDisplayUI.cs @@ -3,8 +3,10 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Net.Sockets; using System.Text.Json; using System.Text.Json.Serialization; +using CalamityMod.Packets; using CalamityMod.UI.DialogueDisplay.DialogueEvents; using CalamityMod.UI.DialogueDisplay.DisplayEffects; using CalamityMod.UI.DialogueDisplay.TextEffects; @@ -22,6 +24,7 @@ using Terraria.ModLoader; using Terraria.UI; using Terraria.UI.Chat; using static System.Runtime.InteropServices.JavaScript.JSType; +using static CalamityMod.Packets.StartDialogueDisplayPacket; using static ReLogic.Graphics.DynamicSpriteFont; namespace CalamityMod.UI.DialogueDisplay @@ -63,8 +66,13 @@ namespace CalamityMod.UI.DialogueDisplay { if (dialog.entity.active) dialog.ui.Position = dialog.entity.Center; - else + else if (ui.DisplayEffects.DespawnWithAttachedNPC) dialog.ui.ClosingDialogue = true; + else + { + dialog.ui.Position = dialog.entity.Center; + dialog.entity = null; + } } if (dialog.upTime != -1) @@ -911,6 +919,43 @@ namespace CalamityMod.UI.DialogueDisplay internal static UserInterface UI; + public enum DisplayEffectID + { + Invalid = -1, + None, + AlwaysOnScreen, + BossText, + Built, + WhisperingPearls + } + + public static DisplayEffectID GetID(object obj) + { + if (obj is not DisplayEffect) + return DisplayEffectID.Invalid; + + return obj switch + { + AlwaysOnScreen => DisplayEffectID.AlwaysOnScreen, + BossText => DisplayEffectID.BossText, + BuiltEffect => DisplayEffectID.Built, + WhisperingPearlEffects => DisplayEffectID.WhisperingPearls, + _ => DisplayEffectID.None + }; + } + + public static DisplayEffect GetEffect(DisplayEffectID id) + { + return id switch + { + DisplayEffectID.AlwaysOnScreen => new AlwaysOnScreen(), + DisplayEffectID.BossText => new BossText(), + DisplayEffectID.Built => new BuiltEffect(), + DisplayEffectID.WhisperingPearls => new WhisperingPearlEffects(), + _ => new DisplayEffect() + }; + } + public override void Load() { if (!Main.dedServ) @@ -1009,8 +1054,26 @@ namespace CalamityMod.UI.DialogueDisplay /// /// The name of the dialogue's localization key /// The position of the text in the world - public static int StartDialogue(string name, Vector2 startPosition, int startIndex = 0, int Uptime = -1, bool progressDialogue = true, DisplayEffect effects = null, float wrapWidth = -1) + public static int StartDialogue(string name, Vector2 startPosition, int startIndex = 0, int Uptime = -1, bool progressDialogue = true, DisplayEffect effects = null, float wrapWidth = -1, int toClient = -1, int ignoreClient = -1) { + if (Main.dedServ) + { + StartDialogueDisplayPacket.Send(name, progressDialogue, startPosition, startIndex, Uptime, GetID(effects), wrapWidth, toClient, ignoreClient); + return -1; + } + else if (Main.netMode == NetmodeID.SinglePlayer) + { + return StartDialogueOnClient(name, startPosition, startIndex, Uptime, progressDialogue, effects, wrapWidth); + } + + return -1; + } + + public static int StartDialogueOnClient(string name, Vector2 startPosition, int startIndex = 0, int Uptime = -1, bool progressDialogue = true, DisplayEffect effects = null, float wrapWidth = -1) + { + if (Main.dedServ) + return -1; + UI ??= new(); State ??= new(); effects ??= new DisplayEffect(); @@ -1048,10 +1111,28 @@ namespace CalamityMod.UI.DialogueDisplay /// The name of the dialogue's localization key /// The entity this dialogue will appear with /// The entity this dialogue will appear with - public static int StartDialogue(string name, Entity entity, int startIndex = 0, int Uptime = -1, bool progressDialogue = true, DisplayEffect effects = null, float wrapWidth = -1) + public static int StartDialogue(string name, Entity entity, int startIndex = 0, int Uptime = -1, bool progressDialogue = true, DisplayEffect effects = null, float wrapWidth = -1, int toClient = -1, int ignoreClient = -1) { - UI ??= new(); - State ??= new(); + if (Main.dedServ) + { + StartDialogueDisplayPacket.Send(name, progressDialogue, entity is NPC ? EntityType.NPC : entity is Player ? EntityType.Player : EntityType.Projectile, entity is Projectile p ? p.identity : entity.whoAmI, startIndex, Uptime, GetID(effects), wrapWidth, toClient, ignoreClient); + return -1; + } + else if (Main.netMode == NetmodeID.SinglePlayer) + { + return StartDialogueOnClient(name, entity, startIndex, Uptime, progressDialogue, effects, wrapWidth); + } + + return -1; + } + + public static int StartDialogueOnClient(string name, Entity entity, int startIndex = 0, int Uptime = -1, bool progressDialogue = true, DisplayEffect effects = null, float wrapWidth = -1) + { + if (Main.dedServ) + return -1; + + UI ??= new (); + State ??= new (); effects ??= new DisplayEffect(); DialogueTextData textData = Deserialize(name); @@ -1066,9 +1147,9 @@ namespace CalamityMod.UI.DialogueDisplay }; int slot; - for (slot = 0; slot <= DialogueDisplayUI.Dialogues.Count; slot++) - if (!DialogueDisplayUI.Dialogues.ContainsKey(slot)) - break; + for (slot = 0; slot <= DialogueDisplayUI.Dialogues.Count; slot++) + if (!DialogueDisplayUI.Dialogues.ContainsKey(slot)) + break; DialogueDisplayUI.Dialogues.Add(slot, (name, display, textData, entity, Uptime)); From 29a269e3c65348139dac5ee37af1fcfd4a0916b9 Mon Sep 17 00:00:00 2001 From: Big E Date: Fri, 26 Dec 2025 03:37:58 -0500 Subject: [PATCH 25/53] + Added option to keep dialogue up after the associated NPC has despawned --- UI/DialogueDisplay/DisplayEffects/BossText.cs | 3 ++- UI/DialogueDisplay/DisplayEffects/DisplayEffect.cs | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/UI/DialogueDisplay/DisplayEffects/BossText.cs b/UI/DialogueDisplay/DisplayEffects/BossText.cs index 69dde0be01..1085ad8e35 100644 --- a/UI/DialogueDisplay/DisplayEffects/BossText.cs +++ b/UI/DialogueDisplay/DisplayEffects/BossText.cs @@ -7,9 +7,10 @@ namespace CalamityMod.UI.DialogueDisplay.DisplayEffects { public class BossText : DisplayEffect { - Vector2 lastPosition = Vector2.Zero; public override bool FadeWhenTooFar => false; + public override bool DespawnWithAttachedNPC => false; + public override Vector2 TextOffsetFromStart(Vector2 startPos, Vector2 textSize) { Vector2 playerPos = Main.LocalPlayer.Center; diff --git a/UI/DialogueDisplay/DisplayEffects/DisplayEffect.cs b/UI/DialogueDisplay/DisplayEffects/DisplayEffect.cs index d4cb2b60d3..109c2cb7f8 100644 --- a/UI/DialogueDisplay/DisplayEffects/DisplayEffect.cs +++ b/UI/DialogueDisplay/DisplayEffects/DisplayEffect.cs @@ -9,6 +9,8 @@ namespace CalamityMod.UI.DialogueDisplay.DisplayEffects public virtual bool FadeWhenTooFar => true; + public virtual bool DespawnWithAttachedNPC => true; + public virtual float FadeBuffer => 150f; public virtual float FadeDistance => 150f; From 57f92cccce37317aa8b9eb9d3b4505eabf2a8c67 Mon Sep 17 00:00:00 2001 From: Big E Date: Fri, 26 Dec 2025 03:38:27 -0500 Subject: [PATCH 26/53] + Fixed issues with Devourer of Gods spawn text and Dialogue Display --- Items/SummonItems/CosmicWorm.cs | 15 --------------- NPCs/DevourerofGods/DevourerofGodsHead.cs | 13 ++++++++++++- 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/Items/SummonItems/CosmicWorm.cs b/Items/SummonItems/CosmicWorm.cs index cc2aa24914..fc73ca9930 100644 --- a/Items/SummonItems/CosmicWorm.cs +++ b/Items/SummonItems/CosmicWorm.cs @@ -47,23 +47,8 @@ namespace CalamityMod.Items.SummonItems if (Main.dedServ) return true; - string key = "Mods.CalamityMod.Status.Boss.DoGSpawn"; - string spawnText = Language.GetTextValue(key); - Color messageColor = Color.Cyan; - Main.NewText(spawnText, messageColor); - /* - var subtitleID = CombatText.NewText(player.Hitbox, messageColor, spawnText, true); - if (subtitleID < Main.maxCombatText) - { - var localPlayer = Main.LocalPlayer.Calamity(); - localPlayer.subtitletext = Main.combatText[subtitleID]; - localPlayer.subtitleColors = [Color.Cyan, Color.Fuchsia]; - } - */ - NPC n = CalamityUtils.SpawnBossOnPosUsingItem(player, (int)player.Center.X, (int)player.Center.Y - 1600, DevourerofGodsHead.SpawnSound); - DialogueDisplaySystem.StartDialogue("DevourerOfGods.Phases", n, 0, 120, false, new BossText()); return true; } diff --git a/NPCs/DevourerofGods/DevourerofGodsHead.cs b/NPCs/DevourerofGods/DevourerofGodsHead.cs index 08de745aa7..c0dd1c3eb5 100644 --- a/NPCs/DevourerofGods/DevourerofGodsHead.cs +++ b/NPCs/DevourerofGods/DevourerofGodsHead.cs @@ -33,12 +33,14 @@ using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; using Terraria; using Terraria.Audio; +using Terraria.DataStructures; using Terraria.GameContent; using Terraria.GameContent.Bestiary; using Terraria.GameContent.Events; using Terraria.GameContent.ItemDropRules; using Terraria.Graphics.Shaders; using Terraria.ID; +using Terraria.Localization; using Terraria.ModLoader; namespace CalamityMod.NPCs.DevourerofGods @@ -304,6 +306,15 @@ namespace CalamityMod.NPCs.DevourerofGods rotation = NPC.rotation; } + public override void OnSpawn(IEntitySource source) + { + string key = "Mods.CalamityMod.Status.Boss.DoGSpawn"; + Color messageColor = Color.Cyan; + CalamityUtils.BroadcastLocalizedText(key, messageColor); + + DialogueDisplaySystem.StartDialogue("DevourerOfGods.Phases", NPC, 0, 120, false, new BossText()); + } + public override void SendExtraAI(BinaryWriter writer) { bool wasDyingBefore = Dying; @@ -2860,7 +2871,7 @@ namespace CalamityMod.NPCs.DevourerofGods target.Calamity().dogTextCooldown = 60; */ - DialogueDisplaySystem.StartDialogue(DialogueGroup, NPC, DialogueIndex, 60, false, new BossText()); + DialogueDisplaySystem.StartDialogueOnClient(DialogueGroup, NPC, DialogueIndex, 60, false, new BossText()); } target.Calamity().DoGHeadHitCounter++; } From 8a19006d15f9a1ce2164a23f300fcc3cacb87376 Mon Sep 17 00:00:00 2001 From: Big E Date: Fri, 26 Dec 2025 14:05:50 -0500 Subject: [PATCH 27/53] + PR Review Fixes --- Packets/StartDialogueDisplayPacket.cs | 43 +++++++++++---------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/Packets/StartDialogueDisplayPacket.cs b/Packets/StartDialogueDisplayPacket.cs index 0cc1812a65..a96cbdd738 100644 --- a/Packets/StartDialogueDisplayPacket.cs +++ b/Packets/StartDialogueDisplayPacket.cs @@ -42,7 +42,7 @@ namespace CalamityMod.Packets packet.Send(toClient, ignoreClient); } - public enum EntityType + public enum EntityType : byte { NPC, Player, @@ -59,7 +59,7 @@ namespace CalamityMod.Packets packet.Write(name); packet.WriteFlags(progressDialogue, true); - packet.WriteFlags(type == EntityType.NPC, type == EntityType.Player); + packet.Write((byte)type); packet.Write(entity); packet.Write(index); packet.Write(uptime); @@ -72,36 +72,16 @@ namespace CalamityMod.Packets public override void HandlePacket(in BinaryReader packet, int sender) { // Only receive info as clients - if (Main.netMode != NetmodeID.MultiplayerClient) - { - packet.ReadString(); - packet.ReadFlags(out _, out bool n); - - if (n) - { - packet.ReadFlags(out _, out _); - packet.ReadInt32(); - } - else - packet.ReadPackedVector2(); - - packet.ReadInt32(); - packet.ReadInt32(); - packet.ReadByte(); - packet.ReadSingle(); - return; - } string name = packet.ReadString(); packet.ReadFlags(out bool progressDialogue, out bool hasEntity); int entity = -1; Vector2 pos = Vector2.zeroVector; - bool isNpc = false; - bool isPlayer = false; + EntityType type = EntityType.NPC; if (hasEntity) { - packet.ReadFlags(out isNpc, out isPlayer); + type = (EntityType)packet.ReadByte(); entity = packet.ReadInt32(); } else @@ -112,10 +92,23 @@ namespace CalamityMod.Packets byte effect = packet.ReadByte(); float wrapWidth = packet.ReadSingle(); + if (Main.netMode != NetmodeID.MultiplayerClient) + return; + DisplayEffect de = GetEffect((DisplayEffectID)effect); if (hasEntity) - StartDialogueOnClient(name, isNpc ? Main.npc[entity] : isPlayer ? Main.player[entity] : Main.projectile.FirstOrDefault(p => p.identity == entity), index, uptime, progressDialogue, de, wrapWidth); + { + Entity e = type switch + { + EntityType.NPC => Main.npc[entity], + EntityType.Player => Main.player[entity], + EntityType.Projectile => Main.projectile.FirstOrDefault(p => p.identity == entity), + _ => null + }; + + StartDialogueOnClient(name, e, index, uptime, progressDialogue, de, wrapWidth); + } else StartDialogueOnClient(name, pos, index, uptime, progressDialogue, de, wrapWidth); From 7547c5ba9d5af860d393c92f63f84be47e507db3 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Tue, 30 Dec 2025 02:16:22 +0900 Subject: [PATCH 28/53] Fully Remove MiracleBlight Renderer --- Buffs/DamageOverTime/MiracleBlight.cs | 76 ++++++++++++- .../MiracleBlightRenderer.cs | 105 ------------------ NPCs/CalamityGlobalNPC.cs | 5 - 3 files changed, 75 insertions(+), 111 deletions(-) delete mode 100644 Graphics/Renderers/CalamityRenderers/MiracleBlightRenderer.cs diff --git a/Buffs/DamageOverTime/MiracleBlight.cs b/Buffs/DamageOverTime/MiracleBlight.cs index bc2f149418..e4cb75a7ea 100644 --- a/Buffs/DamageOverTime/MiracleBlight.cs +++ b/Buffs/DamageOverTime/MiracleBlight.cs @@ -1,8 +1,16 @@ -using CalamityMod.DataStructures; +using System.Collections.Generic; +using CalamityMod.DataStructures; +using CalamityMod.NPCs; +using CalamityMod.NPCs.ExoMechs.Ares; using CalamityMod.Particles; +using CalamityMod.Utilities.Daybreak; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using ReLogic.Content; using Terraria; using Terraria.DataStructures; +using Terraria.Graphics.Shaders; using Terraria.ID; using Terraria.ModLoader; @@ -14,6 +22,33 @@ namespace CalamityMod.Buffs.DamageOverTime { EnemyLostRegen = 3000 }; + + public static Asset ShaderTexture => field ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Neurons"); + + public static List ExcludedNPCsForShader => new() + { + // TODO: Remove this list if possible + + // List the reason why the NPC(s) are excluded :) + + // The particle sets break with the visuals and this is the easiest way to fix this that isn't stupidly complex. + ModContent.NPCType(), + ModContent.NPCType(), + ModContent.NPCType(), + ModContent.NPCType(), + ModContent.NPCType(), + + // Breaks with being behind tiles, and causes a funny interaction where his head goes behind his neck. + NPCID.MoonLordCore, + NPCID.MoonLordHand, + NPCID.MoonLordHead + }; + + public override void Load() + { + On_Main.DrawNPC += DrawForNPC; + } + public override void SetStaticDefaults() { Main.debuff[Type] = true; @@ -96,5 +131,44 @@ namespace CalamityMod.Buffs.DamageOverTime GeneralParticleHandler.SpawnParticle(exoEnergy); } } + + private static void DrawForNPC(On_Main.orig_DrawNPC orig, Main self, int iNPCIndex, bool behindTiles) + { + var npc = Main.npc[iNPCIndex]; + + if (ExcludedNPCsForShader.Contains(npc.type)) + { + orig(self, iNPCIndex, behindTiles); + return; + } + + if (!CalamityDrawParameterNPC.DrawingMiracleBlight[npc.whoAmI]) + { + orig(self, iNPCIndex, behindTiles); + return; + } + + using (Main.spriteBatch.Scope()) + { + using var lease = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); + using (lease.Scope(clearColor: Color.Transparent)) + { + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, Main.Rasterizer, null, Main.Transform); + orig(self, iNPCIndex, behindTiles); + Main.spriteBatch.End(); + } + + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise); + + var blightShader = GameShaders.Misc["CalamityMod:MiracleBlight"]; + blightShader.UseImage1(ShaderTexture); + blightShader.UseOpacity(0.7f); + blightShader.Apply(); + + Main.spriteBatch.Draw(lease.Target, Vector2.Zero, Color.White); + + Main.spriteBatch.End(); + } + } } } diff --git a/Graphics/Renderers/CalamityRenderers/MiracleBlightRenderer.cs b/Graphics/Renderers/CalamityRenderers/MiracleBlightRenderer.cs deleted file mode 100644 index 2c0fb4dcfa..0000000000 --- a/Graphics/Renderers/CalamityRenderers/MiracleBlightRenderer.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System.Collections.Generic; -using CalamityMod.Enums; -using CalamityMod.NPCs; -using CalamityMod.NPCs.ExoMechs.Ares; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using Terraria; -using Terraria.Graphics.Shaders; -using Terraria.ID; -using Terraria.ModLoader; - -namespace CalamityMod.Graphics.Renderers.CalamityRenderers -{ - public class MiracleBlightRenderer : BaseRenderer - { - #region Fields/Properties - /// - /// Add NPCs to this if they break with the miracle blight shader. - /// - public static List ExcludedNPCs => new() - { - // List the reason why the NPC(s) are excluded :) - - // The particle sets break with the visuals and this is the easiest way to fix this that isn't stupidly complex. - ModContent.NPCType(), - ModContent.NPCType(), - ModContent.NPCType(), - ModContent.NPCType(), - ModContent.NPCType(), - - // Breaks with being behind tiles, and causes a funny interaction where his head goes behind his neck. - NPCID.MoonLordCore, - NPCID.MoonLordHand, - NPCID.MoonLordHead - }; - - /// - /// Used to determine whether the npc should return true in predraw or not, for exclusively drawing to the drawer target. - /// - public static bool ActuallyDoPreDraw - { - get; - private set; - } - - public override GeneralDrawLayer Layer => GeneralDrawLayer.AfterNPCs; - - // Unsure whether its more performant to always draw, or to check if any NPC actually has the debuff. - public override bool ShouldDraw => true; - #endregion - - #region Methods - /// - /// Checks if the provided npc is eligible to be drawn with the miracle blight visual effect. - /// - /// The NPC to check - /// If the NPC is eligible - public static bool ValidToDraw(NPC npc) - { - // Do not draw inactive npcs, or ones with weird MP types less than or equal to 0. - if (!npc.active || npc.type <= NPCID.None) - return false; - - if (!CalamityDrawParameterNPC.DrawingMiracleBlight[npc.whoAmI]) - return false; - - return true; - } - - public override void DrawToTarget(SpriteBatch spriteBatch) - { - // Indicate that NPCs with miracle blight should draw. - ActuallyDoPreDraw = true; - - // Draw every npc to a single target that should have the miracle blight visual. - foreach (NPC npc in Main.ActiveNPCs) - { - // Extra check to ensure that index errors will not occur. If not in range, something has gone wrong and the loop should terminate. - if (!Main.npc.IndexInRange(npc.whoAmI)) - break; - - if (ValidToDraw(npc)) - Main.instance.DrawNPC(npc.whoAmI, npc.behindTiles); - } - - // Indicate that NPCs with miracle blight should no longer draw. - ActuallyDoPreDraw = false; - } - - public override void DrawTarget(SpriteBatch spriteBatch) - { - // Apply the shader and draw the target. - var blightShader = GameShaders.Misc["CalamityMod:MiracleBlight"]; - blightShader.SetShaderTexture(ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Neurons"), 1); - blightShader.UseOpacity(0.7f); - blightShader.Apply(); - - spriteBatch.Draw(MainTarget.Target, Vector2.Zero, Color.White); - - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise); - } - #endregion - } -} diff --git a/NPCs/CalamityGlobalNPC.cs b/NPCs/CalamityGlobalNPC.cs index 9976b021c4..d3597de092 100644 --- a/NPCs/CalamityGlobalNPC.cs +++ b/NPCs/CalamityGlobalNPC.cs @@ -12,7 +12,6 @@ using CalamityMod.DataStructures; using CalamityMod.Dusts; using CalamityMod.Events; using CalamityMod.Graphics.Metaballs; -using CalamityMod.Graphics.Renderers.CalamityRenderers; using CalamityMod.Items.Accessories; using CalamityMod.Items.Accessories.Vanity; using CalamityMod.Items.Armor.PlagueReaper; @@ -5380,10 +5379,6 @@ namespace CalamityMod.NPCs } else ManaBurnFireDrawer = null; - - // Only draw the NPC if told to by the miracle blight drawer. - if (MiracleBlightRenderer.ValidToDraw(npc)) - return MiracleBlightRenderer.ActuallyDoPreDraw; } if (Main.zenithWorld) From 7f3ba9b99c1699b1d45576f53d8762bcc521bf54 Mon Sep 17 00:00:00 2001 From: CongratsIsTrash <1q2w3e4dasd@gmail.com> Date: Mon, 29 Dec 2025 17:19:16 -0500 Subject: [PATCH 29/53] Changed variable name --- NPCs/CalamityGlobalTownNPC.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/NPCs/CalamityGlobalTownNPC.cs b/NPCs/CalamityGlobalTownNPC.cs index 469bf84c6a..1c1f3e6717 100644 --- a/NPCs/CalamityGlobalTownNPC.cs +++ b/NPCs/CalamityGlobalTownNPC.cs @@ -895,7 +895,7 @@ namespace CalamityMod.NPCs #region NPC Chat public override void GetChat(NPC npc, ref string chat) { - int permadong = NPC.FindFirstNPC(NPCType()); + int permafrost = NPC.FindFirstNPC(NPCType()); int seahorse = NPC.FindFirstNPC(NPCType()); int thief = NPC.FindFirstNPC(NPCType()); int angelstatue = NPC.FindFirstNPC(NPCID.Merchant); @@ -959,8 +959,8 @@ namespace CalamityMod.NPCs break; case NPCID.DyeTrader: - if (Main.rand.NextBool(5) && permadong != -1) - chat = CalamityUtils.GetText("Vanilla.DyeTraderChat.Archmage").Format(Main.npc[permadong].GivenName); + if (Main.rand.NextBool(5) && permafrost != -1) + chat = CalamityUtils.GetText("Vanilla.DyeTraderChat.Archmage").Format(Main.npc[permafrost].GivenName); else if (Main.rand.NextBool(5)) chat = CalamityUtils.GetTextValue("Vanilla.DyeTraderChat.Normal"); break; @@ -1010,8 +1010,8 @@ namespace CalamityMod.NPCs chat = CalamityUtils.GetTextValue("Vanilla.PainterChat.Crimson"); if (Main.rand.NextBool(4) && Main.LocalPlayer.ZoneSnow) { - if (Main.rand.NextBool() && permadong != -1) - chat = CalamityUtils.GetText("Vanilla.PainterChat.Archmage").Format(Main.npc[permadong].GivenName); + if (Main.rand.NextBool() && permafrost != -1) + chat = CalamityUtils.GetText("Vanilla.PainterChat.Archmage").Format(Main.npc[permafrost].GivenName); else chat = CalamityUtils.GetTextValue("Vanilla.PainterChat.Tundra"); } From a20ddc6ab68eda24443859893f2566677e30ec5a Mon Sep 17 00:00:00 2001 From: Flowaria Date: Tue, 30 Dec 2025 12:03:35 +0900 Subject: [PATCH 30/53] Reorganized Conditions --- Buffs/DamageOverTime/MiracleBlight.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Buffs/DamageOverTime/MiracleBlight.cs b/Buffs/DamageOverTime/MiracleBlight.cs index e4cb75a7ea..448b4616a7 100644 --- a/Buffs/DamageOverTime/MiracleBlight.cs +++ b/Buffs/DamageOverTime/MiracleBlight.cs @@ -136,13 +136,13 @@ namespace CalamityMod.Buffs.DamageOverTime { var npc = Main.npc[iNPCIndex]; - if (ExcludedNPCsForShader.Contains(npc.type)) + if (!CalamityDrawParameterNPC.DrawingMiracleBlight[npc.whoAmI]) { orig(self, iNPCIndex, behindTiles); return; } - if (!CalamityDrawParameterNPC.DrawingMiracleBlight[npc.whoAmI]) + if (ExcludedNPCsForShader.Contains(npc.type)) { orig(self, iNPCIndex, behindTiles); return; From 84d94322bd94fb9a202669d2e57657fe156206d1 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Tue, 30 Dec 2025 12:06:06 +0900 Subject: [PATCH 31/53] Add Load/Unload override to VanillaAIOverride --- NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs b/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs index 6fdff21321..13fb90fdc4 100644 --- a/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs +++ b/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs @@ -4,7 +4,6 @@ using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.ModLoader; using Terraria.ModLoader.IO; -using Terraria.WorldBuilding; namespace CalamityMod.NPCs.VanillaNPCAIOverrides { @@ -14,16 +13,21 @@ namespace CalamityMod.NPCs.VanillaNPCAIOverrides public bool DisableMultiplayerSmoothing { get; set; } public virtual bool EnableMultiplayerSmoothingAheadOfAI => false; - public void Load(Mod mod) + void ILoadable.Load(Mod mod) { CalamityVanillaAIOverrideNPC.RegisterNetID(this); + Load(); } - public void Unload() + void ILoadable.Unload() { - + Unload(); } + public virtual void Load() { } + + public virtual void Unload() { } + public abstract bool AI(Mod mod); public virtual void SetDefaults(Mod mod) { } From 907d710ac10046d0ea4769c142253bfab3af86dc Mon Sep 17 00:00:00 2001 From: Nathanael Overton Date: Mon, 29 Dec 2025 22:32:23 -0500 Subject: [PATCH 32/53] window title variant --- Localization/en-US/Mods.CalamityMod.UI.WindowTitle.hjson | 1 + 1 file changed, 1 insertion(+) diff --git a/Localization/en-US/Mods.CalamityMod.UI.WindowTitle.hjson b/Localization/en-US/Mods.CalamityMod.UI.WindowTitle.hjson index e211a8ab7b..b6aef90746 100644 --- a/Localization/en-US/Mods.CalamityMod.UI.WindowTitle.hjson +++ b/Localization/en-US/Mods.CalamityMod.UI.WindowTitle.hjson @@ -40,3 +40,4 @@ 39: Terraria: Code merged without looking 40: Terraria: Endless Calamity 41: Terraria: Throwing is dead, long live rogue +42: Terraria: A Quick One Before the Nameless Serpent Devours Azafure From 57c1eea33b2d46ea8ed988ed9b66c716ee5799a4 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Tue, 30 Dec 2025 12:24:32 +0900 Subject: [PATCH 33/53] Remove DeerclopsShadowRenderer; Moved to rev+ DeerclopsAI itself --- .../DeerclopsShadowRenderer.cs | 76 ------------------- .../Bosses/DeerclopsAI.cs | 62 +++++++++++++++ 2 files changed, 62 insertions(+), 76 deletions(-) delete mode 100644 Graphics/Renderers/CalamityRenderers/DeerclopsShadowRenderer.cs diff --git a/Graphics/Renderers/CalamityRenderers/DeerclopsShadowRenderer.cs b/Graphics/Renderers/CalamityRenderers/DeerclopsShadowRenderer.cs deleted file mode 100644 index c2adc4bbac..0000000000 --- a/Graphics/Renderers/CalamityRenderers/DeerclopsShadowRenderer.cs +++ /dev/null @@ -1,76 +0,0 @@ -using CalamityMod.Enums; -using CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using Terraria; -using Terraria.GameContent; -using Terraria.Graphics.Shaders; - -namespace CalamityMod.Graphics.Renderers.CalamityRenderers -{ - public class DeerclopsShadowRenderer : BaseRenderer - { - #region Fields/Properties - - public override GeneralDrawLayer Layer => GeneralDrawLayer.AfterEverything; - - public static NPC Deerclops => Main.npc[NPC.deerclopsBoss]; - - // Should only draw if not in the main menu, deerclops is active or the border is fading post-death, - // It's rev+ and the boolean for drawing the border is true. - public override bool ShouldDraw => !Main.gameMenu && DeerclopsAI.borderScalar > 0f && DeerclopsAI.shouldDrawEnrageBorder; - #endregion - - #region Methods - public override void DrawToTarget(SpriteBatch spriteBatch) - { - bool shouldDraw; - var deerclopsInactive = false; - if (NPC.deerclopsBoss >= 0 && NPC.deerclopsBoss.WithinBounds(Main.npc.Length)) - { - shouldDraw = Deerclops.HasValidTarget; - } - else - { - shouldDraw = DeerclopsAI.borderScalar > 0f; - deerclopsInactive = true; - } - - if (shouldDraw) - { - var minRadius = DeerclopsAI.innerBorder; - var maxRadius = DeerclopsAI.outerBorder; - - // Begin drawing the shadow - var blackTile = TextureAssets.MagicPixel; - - var shader = GameShaders.Misc["CalamityMod:DeerclopsShadowShader"].Shader; - shader.Parameters["minRadius"].SetValue(minRadius); - shader.Parameters["maxRadius"].SetValue(maxRadius); - shader.Parameters["anchorPoint"].SetValue(DeerclopsAI.lastDeerclopsPosition); - shader.Parameters["screenPosition"].SetValue(Main.screenPosition); - shader.Parameters["screenSize"].SetValue(Main.ScreenSize.ToVector2()); - shader.Parameters["maxOpacity"].SetValue(DeerclopsAI.borderScalar); - - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, shader, Main.Transform); - - Rectangle rekt = new(Main.screenWidth / 2, Main.screenHeight / 2, Main.screenWidth, Main.screenHeight); - spriteBatch.Draw(blackTile.Value, rekt, null, default, 0f, blackTile.Value.Size() * 0.5f, 0, 0f); - - // Shadow drawing complete - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise); - } - - if (deerclopsInactive) - { - // Push the border away and fade out when deerclops is deadge - DeerclopsAI.borderScalar = MathHelper.Clamp(DeerclopsAI.borderScalar - 0.015f, 0f, 1f); - DeerclopsAI.innerBorder += 30f; - DeerclopsAI.outerBorder += 30f; - } - } - #endregion - } -} diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs index f43a9e772c..f3bb4594de 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs @@ -1,12 +1,16 @@ using System; using CalamityMod.Events; +using CalamityMod.Systems.Graphic; using CalamityMod.World; using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.Audio; using Terraria.DataStructures; using Terraria.Enums; +using Terraria.GameContent; using Terraria.Graphics.CameraModifiers; +using Terraria.Graphics.Shaders; using Terraria.ID; using Terraria.ModLoader; @@ -31,6 +35,64 @@ namespace CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses public static int IceSpikeDamage = 16; // 64 (buffed from 52) public static int HandDamage = 13; // 52 (buffed from 40) + public override void Load() + { + GeneralDrawLayerSystem.OnAfterEverything += DrawDeerclopsShadow; + } + + public override void Unload() + { + GeneralDrawLayerSystem.OnAfterEverything -= DrawDeerclopsShadow; + } + + private static void DrawDeerclopsShadow() + { + bool shouldDraw; + var deerclopsInactive = false; + if (NPC.deerclopsBoss >= 0 && NPC.deerclopsBoss.WithinBounds(Main.npc.Length)) + { + shouldDraw = Main.npc[NPC.deerclopsBoss].HasValidTarget; + } + else + { + shouldDraw = borderScalar > 0f; + deerclopsInactive = true; + } + + if (shouldDraw) + { + var minRadius = innerBorder; + var maxRadius = outerBorder; + + // Begin drawing the shadow + var blackTile = TextureAssets.MagicPixel; + + var shader = GameShaders.Misc["CalamityMod:DeerclopsShadowShader"].Shader; + shader.Parameters["minRadius"].SetValue(minRadius); + shader.Parameters["maxRadius"].SetValue(maxRadius); + shader.Parameters["anchorPoint"].SetValue(lastDeerclopsPosition); + shader.Parameters["screenPosition"].SetValue(Main.screenPosition); + shader.Parameters["screenSize"].SetValue(Main.ScreenSize.ToVector2()); + shader.Parameters["maxOpacity"].SetValue(borderScalar); + + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, shader, Main.Transform); + + Rectangle rekt = new(Main.screenWidth / 2, Main.screenHeight / 2, Main.screenWidth, Main.screenHeight); + Main.spriteBatch.Draw(blackTile.Value, rekt, null, default, 0f, blackTile.Value.Size() * 0.5f, 0, 0f); + + // Shadow drawing complete + Main.spriteBatch.End(); + } + + if (deerclopsInactive) + { + // Push the border away and fade out when deerclops is deadge + borderScalar = MathHelper.Clamp(borderScalar - 0.015f, 0f, 1f); + innerBorder += 30f; + outerBorder += 30f; + } + } + public override bool AI(Mod mod) { CalamityGlobalNPC calamityGlobalNPC = NPC.Calamity(); From 691fdaf61b9b0ae901cb344615ad53565b353852 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Fri, 26 Dec 2025 22:08:34 +0900 Subject: [PATCH 34/53] Implemented DialogueLoader --- Dialogues/DialogueLoader.cs | 94 ++++++ ...CalamityDialogue.DevourerOfGods.Death.json | 53 ++++ .../CalamityDialogue.DevourerOfGods.Head.json | 94 ++++++ ...alamityDialogue.DevourerOfGods.Phases.json | 47 +++ ...lamityDialogue.DevourerOfGods.Running.json | 36 +++ ....CalamityMod.Dialogue.DevourerOfGods.hjson | 271 ------------------ UI/DialogueDisplay/DialogueDisplayUI.cs | 31 +- 7 files changed, 338 insertions(+), 288 deletions(-) create mode 100644 Dialogues/DialogueLoader.cs create mode 100644 Dialogues/en-US/CalamityDialogue.DevourerOfGods.Death.json create mode 100644 Dialogues/en-US/CalamityDialogue.DevourerOfGods.Head.json create mode 100644 Dialogues/en-US/CalamityDialogue.DevourerOfGods.Phases.json create mode 100644 Dialogues/en-US/CalamityDialogue.DevourerOfGods.Running.json delete mode 100644 Localization/en-US/Mods.CalamityMod.Dialogue.DevourerOfGods.hjson diff --git a/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs new file mode 100644 index 0000000000..5b4bd95f31 --- /dev/null +++ b/Dialogues/DialogueLoader.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using CalamityMod.UI.DialogueDisplay; +using Terraria.Localization; +using Terraria.ModLoader; + +namespace CalamityMod.Dialogues; + +internal record DialogueTextDataEntry(string FilePath, string DialogueKey, DialogueTextData Data); + +internal class DialogueLoader : ModSystem +{ + private const string DialogueFilePrefix = "CalamityDialogue."; + + private static readonly Dictionary _DialogueLookup = []; + + public override void Load() => _DialogueLookup.Clear(); + + public override void Unload() => _DialogueLookup.Clear(); + + public static bool TryGetDialogue(string dialogueKey, out DialogueTextData data) + { + return _DialogueLookup.TryGetValue(dialogueKey, out data); + } + + public override void OnLocalizationsLoaded() + { + _DialogueLookup.Clear(); + + foreach (var entry in GetDialogueTextDatas(Mod, GameCulture.DefaultCulture)) + { + _DialogueLookup[entry.DialogueKey] = entry.Data; + } + + var activeCulture = LanguageManager.Instance.ActiveCulture; + foreach (var mod in ModLoader.Mods.Where(mod => mod != Mod)) + { + foreach (var entry in GetDialogueTextDatas(mod, activeCulture)) + { + if (!_DialogueLookup.ContainsKey(entry.DialogueKey)) + continue; + + _DialogueLookup[entry.DialogueKey] = entry.Data; + } + } + } + + private static IEnumerable GetDialogueTextDatas(Mod mod, GameCulture targetCulture) + { + foreach (var file in mod.File) + { + if (!Path.GetExtension(file.Name).Equals(".json", StringComparison.InvariantCultureIgnoreCase)) + continue; + + if (!LocalizationLoader.TryGetCultureAndPrefixFromPath(file.Name, out var culture, out var prefix)) + continue; + + string fileName = Path.GetFileNameWithoutExtension(file.Name); + string dialogueKey; + if (fileName.StartsWith($"{prefix}_{DialogueFilePrefix}", StringComparison.InvariantCultureIgnoreCase)) + dialogueKey = fileName[$"{prefix}_{DialogueFilePrefix}".Length..]; + else if (fileName.StartsWith(DialogueFilePrefix, StringComparison.InvariantCultureIgnoreCase)) + dialogueKey = fileName[DialogueFilePrefix.Length..]; + else + continue; + + // Explictly Allow Default Culture File. + // This is for Translation mod that made for non-specified culture + if (culture != targetCulture && culture != GameCulture.DefaultCulture) + continue; + + DialogueTextData data = null; + try + { + using var stream = new StreamReader(mod.File.GetStream(file), Encoding.UTF8); + data = JsonSerializer.Deserialize(stream.BaseStream); + } + catch (Exception e) + { + CalamityMod.Log.Error($"Error while reading DialogueTextData entry: {e}"); + } + + if (data != null) + { + CalamityMod.Log.Info($"Found Dialogue Item: '{mod.Name}', '{file.Name}', '{prefix}', '{culture.Name}'"); + yield return new DialogueTextDataEntry(file.Name, dialogueKey, data); + } + } + } +} diff --git a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Death.json b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Death.json new file mode 100644 index 0000000000..808d9f0d2a --- /dev/null +++ b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Death.json @@ -0,0 +1,53 @@ +{ + "DefaultColor": "6383FF", + "DefaultSpeaker": "DevourerOfGods", + "AlignType": 1, + "TextDelay": 2, + "BasePunctuationDelay": { + "Delay": 10, + "ForceSet": false, + "Locks": false + }, + "PunctuationDelayCap": 30, + "PunctuationDelays": { + "!": { + "Delay": 20, + "ForceSet": true, + "Locks": true + }, + "?": { + "Delay": 20, + "ForceSet": true, + "Locks": true + } + }, + "Pages": [ + { + "TextDelay": 0, + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Tasteless [Pause(0.25)]slop.]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Delicious... A feast worthy of a god!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):And [Shaking:STAY] dead!]]" + ] + }, + { + "TextDelay": 0, + "Lines": [ + "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):WEAK.]]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):[Shaking:PATHETIC.] ALL THAT RUNNING JUST TO DIE TO A [Shaking:SINGLE TOUCH?!]]]" + ] + } + ] +} diff --git a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Head.json b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Head.json new file mode 100644 index 0000000000..23af53b64e --- /dev/null +++ b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Head.json @@ -0,0 +1,94 @@ +{ + "DefaultColor": "6383FF", + "DefaultSpeaker": "DevourerOfGods", + "AlignType": 1, + "TextDelay": 2, + "BasePunctuationDelay": { + "Delay": 10, + "ForceSet": false, + "Locks": false + }, + "PunctuationDelayCap": 30, + "PunctuationDelays": { + "!": { + "Delay": 20, + "ForceSet": true, + "Locks": true + }, + "?": { + "Delay": 20, + "ForceSet": true, + "Locks": true + } + }, + "Pages": [ + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Fall to your knees, worm!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Let's see how much longer you'll last...]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Getting tired yet?]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You'll fall, just like the others!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Give up! It'll be easier for both of us!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Let me end you already!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):This is starting to get ridiculous...!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):How are you doing this?!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Are you playing me for a fool?!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Why won't you [Shaking:DIE?!]]]" + ] + }, + { + "TextDelay": 0, + "Lines": [ + "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):FALL!]]]" + ] + }, + { + "TextDelay": 0, + "Lines": [ + "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):BEGON!]]]" + ] + }, + { + "TextDelay": 0, + "Lines": [ + "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):DIE!]]]" + ] + } + ] +} diff --git a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Phases.json b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Phases.json new file mode 100644 index 0000000000..ea29aca85b --- /dev/null +++ b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Phases.json @@ -0,0 +1,47 @@ +{ + "DefaultColor": "6383FF", + "DefaultSpeaker": "DevourerOfGods", + "AlignType": 1, + "TextDelay": 2, + "BasePunctuationDelay": { + "Delay": 10, + "ForceSet": false, + "Locks": false + }, + "PunctuationDelayCap": 30, + "PunctuationDelays": { + "!": { + "Delay": 20, + "ForceSet": true, + "Locks": true + }, + "?": { + "Delay": 20, + "ForceSet": true, + "Locks": true + } + }, + "Pages": [ + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You are no god...]]", + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):But I shall feast upon your essence regardless!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You've done better than most, but don't get cocky!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):It's not over yet, kid!]]" + ] + }, + { + "Lines": [ + "[Colors(2, 0.5, 00FFFF, FF00FF):[Shaking:[Scale(1.5):A]]][Colors(2, 0.5, FF00FF, 00FFFF):[Shaking(5):[Scale(2): [Pause(0.33)]GOD]]][Colors(2, 0.5, 00FFFF, FF00FF):[Shaking:[Scale(1.5): DOES NOT FEAR]]][Colors(2, 0.5, FF00FF, 00FFFF):[Shaking(5):[Scale(2): [Pause(0.33)]DEATH!]]]" + ] + } + ] +} \ No newline at end of file diff --git a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Running.json b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Running.json new file mode 100644 index 0000000000..697082968b --- /dev/null +++ b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Running.json @@ -0,0 +1,36 @@ +{ + "DefaultColor": "6383FF", + "DefaultSpeaker": "DevourerOfGods", + "AlignType": 1, + "TextDelay": 2, + "BasePunctuationDelay": { + "Delay": 10, + "ForceSet": false, + "Locks": false + }, + "PunctuationDelayCap": 30, + "PunctuationDelays": { + "!": { + "Delay": 20, + "ForceSet": true, + "Locks": true + }, + "?": { + "Delay": 20, + "ForceSet": true, + "Locks": true + } + }, + "Pages": [ + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You can't run forever!]]" + ] + }, + { + "Lines": [ + "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):WHAT'S THE PROBLEM?! CAN'T RUN ANYMORE?!]]]" + ] + } + ] +} diff --git a/Localization/en-US/Mods.CalamityMod.Dialogue.DevourerOfGods.hjson b/Localization/en-US/Mods.CalamityMod.Dialogue.DevourerOfGods.hjson deleted file mode 100644 index e55d20782c..0000000000 --- a/Localization/en-US/Mods.CalamityMod.Dialogue.DevourerOfGods.hjson +++ /dev/null @@ -1,271 +0,0 @@ -Phases: - ''' - { - "DefaultColor": "6383FF", - "DefaultSpeaker": "DevourerOfGods", - "AlignType": 1, - - "TextDelay": 2, - "BasePunctuationDelay": { - "Delay": 10, - "ForceSet": false, - "Locks": false - }, - "PunctuationDelayCap": 30, - "PunctuationDelays": { - "!": { - "Delay": 20, - "ForceSet": true, - "Locks": true - }, - "?": { - "Delay": 20, - "ForceSet": true, - "Locks": true - } - }, - - "Pages": [ - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You are no god...]]", - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):But I shall feast upon your essence regardless!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You've done better than most, but don't get cocky!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):It's not over yet, kid!]]" - ] - }, - - { - "Lines": [ - "[Colors(2, 0.5, 00FFFF, FF00FF):[Shaking:[Scale(1.5):A]]][Colors(2, 0.5, FF00FF, 00FFFF):[Shaking(5):[Scale(2): [Pause(0.33)]GOD]]][Colors(2, 0.5, 00FFFF, FF00FF):[Shaking:[Scale(1.5): DOES NOT FEAR]]][Colors(2, 0.5, FF00FF, 00FFFF):[Shaking(5):[Scale(2): [Pause(0.33)]DEATH!]]]" - ] - } - ] - } - ''' -Death: - ''' - { - "DefaultColor": "6383FF", - "DefaultSpeaker": "DevourerOfGods", - "AlignType": 1, - - "TextDelay": 2, - "BasePunctuationDelay": { - "Delay": 10, - "ForceSet": false, - "Locks": false - }, - "PunctuationDelayCap": 30, - "PunctuationDelays": { - "!": { - "Delay": 20, - "ForceSet": true, - "Locks": true - }, - "?": { - "Delay": 20, - "ForceSet": true, - "Locks": true - } - }, - - "Pages": [ - { - "TextDelay": 0, - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Tasteless [Pause(0.25)]slop.]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Delicious... A feast worthy of a god!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):And [Shaking:STAY] dead!]]" - ] - }, - - { - "TextDelay": 0, - "Lines": [ - "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):WEAK.]]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):[Shaking:PATHETIC.] ALL THAT RUNNING JUST TO DIE TO A [Shaking:SINGLE TOUCH?!]]]" - ] - } - ] - } - ''' -Head: - ''' - { - "DefaultColor": "6383FF", - "DefaultSpeaker": "DevourerOfGods", - "AlignType": 1, - - "TextDelay": 2, - "BasePunctuationDelay": { - "Delay": 10, - "ForceSet": false, - "Locks": false - }, - "PunctuationDelayCap": 30, - "PunctuationDelays": { - "!": { - "Delay": 20, - "ForceSet": true, - "Locks": true - }, - "?": { - "Delay": 20, - "ForceSet": true, - "Locks": true - } - }, - - "Pages": [ - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Fall to your knees, worm!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Let's see how much longer you'll last...]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Getting tired yet?]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You'll fall, just like the others!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Give up! It'll be easier for both of us!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Let me end you already!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):This is starting to get ridiculous...!]]" - ] - - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):How are you doing this?!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Are you playing me for a fool?!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Why won't you [Shaking:DIE?!]]]" - ] - }, - - { - "TextDelay": 0, - "Lines": [ - "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):FALL!]]]" - ] - }, - - { - "TextDelay": 0, - "Lines": [ - "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):BEGON!]]]" - ] - }, - - { - "TextDelay": 0, - "Lines": [ - "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):DIE!]]]" - ] - } - ] - } - ''' -Running: - ''' - { - "DefaultColor": "6383FF", - "DefaultSpeaker": "DevourerOfGods", - "AlignType": 1, - - "TextDelay": 2, - "BasePunctuationDelay": { - "Delay": 10, - "ForceSet": false, - "Locks": false - }, - "PunctuationDelayCap": 30, - "PunctuationDelays": { - "!": { - "Delay": 20, - "ForceSet": true, - "Locks": true - }, - "?": { - "Delay": 20, - "ForceSet": true, - "Locks": true - } - }, - - "Pages": [ - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You can't run forever!]]" - ] - }, - - { - "Lines": [ - "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):WHAT'S THE PROBLEM?! CAN'T RUN ANYMORE?!]]]" - ] - } - ] - } - ''' diff --git a/UI/DialogueDisplay/DialogueDisplayUI.cs b/UI/DialogueDisplay/DialogueDisplayUI.cs index 18eb13319e..0cbef28634 100644 --- a/UI/DialogueDisplay/DialogueDisplayUI.cs +++ b/UI/DialogueDisplay/DialogueDisplayUI.cs @@ -1,25 +1,23 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.IO; using System.Linq; using System.Net.Sockets; using System.Text.Json; using System.Text.Json.Serialization; +using CalamityMod.Dialogues; using CalamityMod.Packets; using CalamityMod.UI.DialogueDisplay.DialogueEvents; using CalamityMod.UI.DialogueDisplay.DisplayEffects; using CalamityMod.UI.DialogueDisplay.TextEffects; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using Microsoft.Xna.Framework.Input; using ReLogic.Content; using ReLogic.Graphics; using Terraria; using Terraria.Audio; using Terraria.GameContent; using Terraria.ID; -using Terraria.Localization; using Terraria.ModLoader; using Terraria.UI; using Terraria.UI.Chat; @@ -536,7 +534,7 @@ namespace CalamityMod.UI.DialogueDisplay foreach (string s in returnString) storedLen += s.Length; - Pauses.Add(index - storedLen - 1, Params[0]); + Pauses.Add(index - storedLen - 1, Params[0]); } else { @@ -985,15 +983,6 @@ namespace CalamityMod.UI.DialogueDisplay UI?.Update(gameTime); } - public static DialogueTextData Deserialize(string name) - { - string json = Language.GetTextValue("Mods.CalamityMod.Dialogue." + name); - - DialogueTextData data = JsonSerializer.Deserialize(json); - - return data; - } - public static Color GetColorFromHex(string hex) { System.Drawing.Color color = System.Drawing.ColorTranslator.FromHtml('#' + hex); @@ -1008,8 +997,8 @@ namespace CalamityMod.UI.DialogueDisplay ///
public static int GetSlot(string name) { - foreach(var pair in DialogueDisplayUI.Dialogues) - if(pair.Value.name == name) + foreach (var pair in DialogueDisplayUI.Dialogues) + if (pair.Value.name == name) return pair.Key; return -1; } @@ -1078,7 +1067,11 @@ namespace CalamityMod.UI.DialogueDisplay State ??= new(); effects ??= new DisplayEffect(); - DialogueTextData textData = Deserialize(name); + if (!DialogueLoader.TryGetDialogue(name, out var textData)) + { + CalamityMod.Log.Error($"Unable to find Dialogue Data for given name: '{name}'"); + return -1; + } if (startIndex >= textData.PageCount) startIndex = textData.PageCount - 1; @@ -1135,7 +1128,11 @@ namespace CalamityMod.UI.DialogueDisplay State ??= new (); effects ??= new DisplayEffect(); - DialogueTextData textData = Deserialize(name); + if (!DialogueLoader.TryGetDialogue(name, out var textData)) + { + CalamityMod.Log.Error($"Unable to find Dialogue Data for given name: '{name}'"); + return -1; + } if (startIndex >= textData.PageCount) startIndex = textData.PageCount - 1; From a375f8b9f60720e3bdde0f2023d72f13d8c4881a Mon Sep 17 00:00:00 2001 From: Flowaria Date: Fri, 26 Dec 2025 22:09:39 +0900 Subject: [PATCH 35/53] null check --- Dialogues/DialogueLoader.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs index 5b4bd95f31..5baedf4d5d 100644 --- a/Dialogues/DialogueLoader.cs +++ b/Dialogues/DialogueLoader.cs @@ -51,6 +51,12 @@ internal class DialogueLoader : ModSystem private static IEnumerable GetDialogueTextDatas(Mod mod, GameCulture targetCulture) { + if (mod == null) + yield break; + + if (mod.File == null) + yield break; + foreach (var file in mod.File) { if (!Path.GetExtension(file.Name).Equals(".json", StringComparison.InvariantCultureIgnoreCase)) From 69b19e7a0b52686c70f695a5b98fad1842f2c293 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Fri, 26 Dec 2025 23:46:41 +0900 Subject: [PATCH 36/53] Added Ability to Extract Dialogue Files --- Dialogues/DialogueLoader.cs | 124 +++++++++++++++++++++++++++++++----- 1 file changed, 108 insertions(+), 16 deletions(-) diff --git a/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs index 5baedf4d5d..d4e9878056 100644 --- a/Dialogues/DialogueLoader.cs +++ b/Dialogues/DialogueLoader.cs @@ -2,29 +2,118 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using System.Text; using System.Text.Json; using CalamityMod.UI.DialogueDisplay; +using MonoMod.Cil; +using MonoMod.RuntimeDetour; using Terraria.Localization; using Terraria.ModLoader; namespace CalamityMod.Dialogues; -internal record DialogueTextDataEntry(string FilePath, string DialogueKey, DialogueTextData Data); +internal record DialogueTextDataEntry( + string FilePath, + string DialogueKey, + DialogueTextData Data + ); internal class DialogueLoader : ModSystem { private const string DialogueFilePrefix = "CalamityDialogue."; - private static readonly Dictionary _DialogueLookup = []; + private static readonly Dictionary _DialogueLookup = []; - public override void Load() => _DialogueLookup.Clear(); + private ILHook _ExtractLocalizationHook; - public override void Unload() => _DialogueLookup.Clear(); + public override void Load() + { + _DialogueLookup.Clear(); + + var method = typeof(LocalizationLoader).GetMethod(nameof(LocalizationLoader.ExtractLocalizationFiles), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); + if (method != null) + { + _ExtractLocalizationHook = new ILHook(method, ExtractDialogueFilesPatch); + _ExtractLocalizationHook.Apply(); + } + } + + public override void Unload() + { + _DialogueLookup.Clear(); + + if (_ExtractLocalizationHook != null) + { + _ExtractLocalizationHook.Undo(); + _ExtractLocalizationHook.Dispose(); + _ExtractLocalizationHook = null; + } + } + + private static void ExtractDialogueFilesPatch(ILContext il) + { + var cursor = new ILCursor(il); + + int pathLdloc = -1; + int modLdloc = -1; + if (!cursor.TryGotoNext(MoveType.After, + i => i.MatchLdloc(out modLdloc), // Mod mod + i => i.MatchLdloc(out pathLdloc), // string path + i => i.MatchCallOrCallvirt(out _), // GameCulture ActiveCulture + i => i.MatchCallOrCallvirt(typeof(LocalizationLoader), nameof(LocalizationLoader.UpdateLocalizationFilesForMod)))) + { + CalamityMod.Log.ILFailure("Force Extract Dialogue Files", $"Unable to locate {nameof(LocalizationLoader.UpdateLocalizationFilesForMod)} call"); + } + + if (modLdloc == -1) + { + CalamityMod.Log.ILFailure("Force Extract Dialogue Files", $"Unable to locate ldloc index for mod"); + } + + if (pathLdloc == -1) + { + CalamityMod.Log.ILFailure("Force Extract Dialogue Files", $"Unable to locate ldloc index for path"); + } + + cursor.EmitLdloc(modLdloc); + cursor.EmitLdloc(pathLdloc); + cursor.EmitDelegate((Mod mod, string path) => + { + if (mod != CalamityMod.Instance) + return; + + var exportPath = Path.Combine(path, "Dialogues", "en-US"); + if (!Directory.Exists(exportPath)) Directory.CreateDirectory(exportPath); + + foreach (var entry in GetDialogueTextDatas(CalamityMod.Instance, GameCulture.DefaultCulture, skipDeserializeData: true)) + { + try + { + using var stream = CalamityMod.Instance.File.GetStream(entry.FilePath); + using var fileStream = File.OpenWrite(Path.Combine(exportPath, Path.GetFileName(entry.FilePath))); + using var writer = new StreamWriter(fileStream, Encoding.UTF8); + using var reader = new StreamReader(stream, Encoding.UTF8); + writer.Write(reader.ReadToEnd()); + } + catch (Exception e) + { + CalamityMod.Log.Error($"Error while exporting DialogueTextData entry: {e}"); + } + } + }); + } public static bool TryGetDialogue(string dialogueKey, out DialogueTextData data) { - return _DialogueLookup.TryGetValue(dialogueKey, out data); + if (_DialogueLookup.TryGetValue(dialogueKey, out var entry)) + { + data = entry.Data; + return true; + } + + data = null; + return false; } public override void OnLocalizationsLoaded() @@ -33,7 +122,7 @@ internal class DialogueLoader : ModSystem foreach (var entry in GetDialogueTextDatas(Mod, GameCulture.DefaultCulture)) { - _DialogueLookup[entry.DialogueKey] = entry.Data; + _DialogueLookup[entry.DialogueKey] = entry; } var activeCulture = LanguageManager.Instance.ActiveCulture; @@ -44,12 +133,12 @@ internal class DialogueLoader : ModSystem if (!_DialogueLookup.ContainsKey(entry.DialogueKey)) continue; - _DialogueLookup[entry.DialogueKey] = entry.Data; + _DialogueLookup[entry.DialogueKey] = entry; } } } - private static IEnumerable GetDialogueTextDatas(Mod mod, GameCulture targetCulture) + private static IEnumerable GetDialogueTextDatas(Mod mod, GameCulture targetCulture, bool skipDeserializeData = false) { if (mod == null) yield break; @@ -80,17 +169,20 @@ internal class DialogueLoader : ModSystem continue; DialogueTextData data = null; - try + if (!skipDeserializeData) { - using var stream = new StreamReader(mod.File.GetStream(file), Encoding.UTF8); - data = JsonSerializer.Deserialize(stream.BaseStream); - } - catch (Exception e) - { - CalamityMod.Log.Error($"Error while reading DialogueTextData entry: {e}"); + try + { + using var stream = new StreamReader(mod.File.GetStream(file), Encoding.UTF8); + data = JsonSerializer.Deserialize(stream.BaseStream); + } + catch (Exception e) + { + CalamityMod.Log.Error($"Error while reading DialogueTextData entry: {e}"); + } } - if (data != null) + if (data != null || skipDeserializeData) { CalamityMod.Log.Info($"Found Dialogue Item: '{mod.Name}', '{file.Name}', '{prefix}', '{culture.Name}'"); yield return new DialogueTextDataEntry(file.Name, dialogueKey, data); From 754bb013be45b97eb8ea32810be78f505472971d Mon Sep 17 00:00:00 2001 From: Flowaria Date: Sat, 27 Dec 2025 00:07:51 +0900 Subject: [PATCH 37/53] - Added Revision Matching - Better Export pathing --- Dialogues/DialogueLoader.cs | 23 +++++++++++++------ ...CalamityDialogue.DevourerOfGods.Death.json | 1 + .../CalamityDialogue.DevourerOfGods.Head.json | 1 + ...alamityDialogue.DevourerOfGods.Phases.json | 1 + ...lamityDialogue.DevourerOfGods.Running.json | 1 + UI/DialogueDisplay/DialogueDisplayUI.cs | 5 ++++ 6 files changed, 25 insertions(+), 7 deletions(-) diff --git a/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs index d4e9878056..ea4d128607 100644 --- a/Dialogues/DialogueLoader.cs +++ b/Dialogues/DialogueLoader.cs @@ -78,20 +78,21 @@ internal class DialogueLoader : ModSystem cursor.EmitLdloc(modLdloc); cursor.EmitLdloc(pathLdloc); - cursor.EmitDelegate((Mod mod, string path) => + cursor.EmitDelegate((Mod mod, string basePath) => { if (mod != CalamityMod.Instance) return; - var exportPath = Path.Combine(path, "Dialogues", "en-US"); - if (!Directory.Exists(exportPath)) Directory.CreateDirectory(exportPath); - foreach (var entry in GetDialogueTextDatas(CalamityMod.Instance, GameCulture.DefaultCulture, skipDeserializeData: true)) { try { + var destFilePath = Path.Combine(basePath, entry.FilePath); + var destDir = Path.GetDirectoryName(destFilePath); + if (!Directory.Exists(destDir)) Directory.CreateDirectory(destDir); + using var stream = CalamityMod.Instance.File.GetStream(entry.FilePath); - using var fileStream = File.OpenWrite(Path.Combine(exportPath, Path.GetFileName(entry.FilePath))); + using var fileStream = File.OpenWrite(destFilePath); using var writer = new StreamWriter(fileStream, Encoding.UTF8); using var reader = new StreamReader(stream, Encoding.UTF8); writer.Write(reader.ReadToEnd()); @@ -130,8 +131,17 @@ internal class DialogueLoader : ModSystem { foreach (var entry in GetDialogueTextDatas(mod, activeCulture)) { - if (!_DialogueLookup.ContainsKey(entry.DialogueKey)) + if (!_DialogueLookup.TryGetValue(entry.DialogueKey, out var oldEntry)) + { + CalamityMod.Log.Warn($"Dialogue Localization was detected but original Dialogue file does not exists. This will not be applied! : '{entry.FilePath}'"); continue; + } + + if (entry.Data.Revision != oldEntry.Data.Revision) + { + CalamityMod.Log.Warn($"Dialogue Localization was detected but revision mismatches. This will not be applied! : '{entry.FilePath}'"); + continue; + } _DialogueLookup[entry.DialogueKey] = entry; } @@ -184,7 +194,6 @@ internal class DialogueLoader : ModSystem if (data != null || skipDeserializeData) { - CalamityMod.Log.Info($"Found Dialogue Item: '{mod.Name}', '{file.Name}', '{prefix}', '{culture.Name}'"); yield return new DialogueTextDataEntry(file.Name, dialogueKey, data); } } diff --git a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Death.json b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Death.json index 808d9f0d2a..3e92c78a0f 100644 --- a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Death.json +++ b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Death.json @@ -1,4 +1,5 @@ { + "Revision": 1, "DefaultColor": "6383FF", "DefaultSpeaker": "DevourerOfGods", "AlignType": 1, diff --git a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Head.json b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Head.json index 23af53b64e..93da2b43ff 100644 --- a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Head.json +++ b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Head.json @@ -1,4 +1,5 @@ { + "Revision": 1, "DefaultColor": "6383FF", "DefaultSpeaker": "DevourerOfGods", "AlignType": 1, diff --git a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Phases.json b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Phases.json index ea29aca85b..3ae52d8b17 100644 --- a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Phases.json +++ b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Phases.json @@ -1,4 +1,5 @@ { + "Revision": 1, "DefaultColor": "6383FF", "DefaultSpeaker": "DevourerOfGods", "AlignType": 1, diff --git a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Running.json b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Running.json index 697082968b..de35cd7052 100644 --- a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Running.json +++ b/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Running.json @@ -1,4 +1,5 @@ { + "Revision": 1, "DefaultColor": "6383FF", "DefaultSpeaker": "DevourerOfGods", "AlignType": 1, diff --git a/UI/DialogueDisplay/DialogueDisplayUI.cs b/UI/DialogueDisplay/DialogueDisplayUI.cs index 0cbef28634..5739c68a8c 100644 --- a/UI/DialogueDisplay/DialogueDisplayUI.cs +++ b/UI/DialogueDisplay/DialogueDisplayUI.cs @@ -1198,6 +1198,11 @@ namespace CalamityMod.UI.DialogueDisplay public int PunctuationDelayCap { get; init; } public Dictionary PunctuationDelays { get; init; } + /// + /// Only used for DialogueLoader + /// + public int Revision { get; init; } + [JsonConstructor] public DialogueTextData(DialoguePage[] Pages, int Page = 0, string DefaultColor = null, string DefaultSpeaker = null, int DefaultScale = 1, Alignment AlignType = 0, int TextDelay = 3, PunctuationData BasePunctuationDelay = null, int PunctuationDelayCap = 60, Dictionary PunctuationDelays = null) { From 9ea07159ed27a00f9548767f213e291022ab0e29 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Sat, 27 Dec 2025 00:11:34 +0900 Subject: [PATCH 38/53] Append Mod name to Error Message --- Dialogues/DialogueLoader.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs index ea4d128607..ff38af9d82 100644 --- a/Dialogues/DialogueLoader.cs +++ b/Dialogues/DialogueLoader.cs @@ -99,7 +99,7 @@ internal class DialogueLoader : ModSystem } catch (Exception e) { - CalamityMod.Log.Error($"Error while exporting DialogueTextData entry: {e}"); + CalamityMod.Log.Error($"Error while exporting DialogueTextData entry ({CalamityMod.Instance}::{entry.FilePath}): {e}"); } } }); @@ -133,13 +133,13 @@ internal class DialogueLoader : ModSystem { if (!_DialogueLookup.TryGetValue(entry.DialogueKey, out var oldEntry)) { - CalamityMod.Log.Warn($"Dialogue Localization was detected but original Dialogue file does not exists. This will not be applied! : '{entry.FilePath}'"); + CalamityMod.Log.Warn($"Dialogue Localization was detected but original Dialogue file does not exists. This will not be applied! : '{mod.Name}::{entry.FilePath}'"); continue; } if (entry.Data.Revision != oldEntry.Data.Revision) { - CalamityMod.Log.Warn($"Dialogue Localization was detected but revision mismatches. This will not be applied! : '{entry.FilePath}'"); + CalamityMod.Log.Warn($"Dialogue Localization was detected but revision mismatches. This will not be applied! : '{mod.Name}::{entry.FilePath}'"); continue; } @@ -188,7 +188,7 @@ internal class DialogueLoader : ModSystem } catch (Exception e) { - CalamityMod.Log.Error($"Error while reading DialogueTextData entry: {e}"); + CalamityMod.Log.Error($"Error while reading DialogueTextData entry ({mod.Name}::{file.Name}): {e}"); } } From f1e5e5fb8612dd8f7a26ffd24c4e5dd5c5fa6ee4 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Sat, 27 Dec 2025 15:48:36 +0900 Subject: [PATCH 39/53] Implemented HotReloading for Dialogue Jsons --- Dialogues/DialogueLoader.cs | 117 ++++++++++++++++++--- Utilities/MainThreadedFileSystemWatcher.cs | 107 +++++++++++++++++++ 2 files changed, 209 insertions(+), 15 deletions(-) create mode 100644 Utilities/MainThreadedFileSystemWatcher.cs diff --git a/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs index ff38af9d82..5a99510fef 100644 --- a/Dialogues/DialogueLoader.cs +++ b/Dialogues/DialogueLoader.cs @@ -5,25 +5,31 @@ using System.Linq; using System.Reflection; using System.Text; using System.Text.Json; +using System.Text.RegularExpressions; using CalamityMod.UI.DialogueDisplay; +using CalamityMod.Utilities; using MonoMod.Cil; using MonoMod.RuntimeDetour; +using Terraria; using Terraria.Localization; using Terraria.ModLoader; +using Terraria.ModLoader.Core; namespace CalamityMod.Dialogues; internal record DialogueTextDataEntry( + Mod ProviderMod, string FilePath, string DialogueKey, DialogueTextData Data ); -internal class DialogueLoader : ModSystem +internal partial class DialogueLoader : ModSystem { private const string DialogueFilePrefix = "CalamityDialogue."; private static readonly Dictionary _DialogueLookup = []; + private static readonly Dictionary _Watchers = []; private ILHook _ExtractLocalizationHook; @@ -39,6 +45,35 @@ internal class DialogueLoader : ModSystem } } + public override void PostSetupContent() + { + foreach (var mod in ModLoader.Mods) + { + string path = Path.Combine(ModCompile.ModSourcePath, mod.Name); + if (!Directory.Exists(path)) + continue; + + var watcher = new MainThreadedFileSystemWatcher() + { + Path = path, + Filter = "*.json", + FileNameFilter = CalamityDialogueFileRegex(), + NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite, + IncludeSubdirectories = true + }; + watcher.Changed += (o, arg) => + { + HandleFileUpdate(mod, arg.FullPath); + }; + watcher.Renamed += (o, arg) => + { + HandleFileUpdate(mod, arg.FullPath); + }; + watcher.EnableRaisingEvents = true; + _Watchers[mod] = watcher; + } + } + public override void Unload() { _DialogueLookup.Clear(); @@ -49,6 +84,14 @@ internal class DialogueLoader : ModSystem _ExtractLocalizationHook.Dispose(); _ExtractLocalizationHook = null; } + + foreach (var watcher in _Watchers.Values) + { + watcher.EnableRaisingEvents = false; + watcher.Dispose(); + } + + _Watchers.Clear(); } private static void ExtractDialogueFilesPatch(ILContext il) @@ -148,6 +191,35 @@ internal class DialogueLoader : ModSystem } } + private static void HandleFileUpdate(Mod mod, string filePath) + { + if (!TryGetDialogueFileInfo(filePath, out _, out _, out var dialogueKey)) + return; + + if (!_DialogueLookup.TryGetValue(dialogueKey, out var existingEntry)) + return; + + if (existingEntry.ProviderMod != mod) + return; + + try + { + using var stream = new StreamReader(File.OpenRead(filePath), Encoding.UTF8); + _DialogueLookup[dialogueKey] = existingEntry with + { + Data = JsonSerializer.Deserialize(stream.BaseStream) + }; + + var hotreloadedMessage = $"Dialogue entry has hot reloaded: '{dialogueKey}', from source: '{filePath}'"; + CalamityMod.Log.Info(hotreloadedMessage); + if (!Main.gameMenu) Main.NewText(hotreloadedMessage); + } + catch (Exception e) + { + CalamityMod.Log.Error($"Error while hot reloading DialogueTextData entry ({filePath}): {e}"); + } + } + private static IEnumerable GetDialogueTextDatas(Mod mod, GameCulture targetCulture, bool skipDeserializeData = false) { if (mod == null) @@ -158,19 +230,7 @@ internal class DialogueLoader : ModSystem foreach (var file in mod.File) { - if (!Path.GetExtension(file.Name).Equals(".json", StringComparison.InvariantCultureIgnoreCase)) - continue; - - if (!LocalizationLoader.TryGetCultureAndPrefixFromPath(file.Name, out var culture, out var prefix)) - continue; - - string fileName = Path.GetFileNameWithoutExtension(file.Name); - string dialogueKey; - if (fileName.StartsWith($"{prefix}_{DialogueFilePrefix}", StringComparison.InvariantCultureIgnoreCase)) - dialogueKey = fileName[$"{prefix}_{DialogueFilePrefix}".Length..]; - else if (fileName.StartsWith(DialogueFilePrefix, StringComparison.InvariantCultureIgnoreCase)) - dialogueKey = fileName[DialogueFilePrefix.Length..]; - else + if (!TryGetDialogueFileInfo(file.Name, out var culture, out var prefix, out var dialogueKey)) continue; // Explictly Allow Default Culture File. @@ -194,8 +254,35 @@ internal class DialogueLoader : ModSystem if (data != null || skipDeserializeData) { - yield return new DialogueTextDataEntry(file.Name, dialogueKey, data); + yield return new DialogueTextDataEntry(mod, file.Name, dialogueKey, data); } } } + + private static bool TryGetDialogueFileInfo(string filePath, out GameCulture culture, out string prefix, out string dialogueKey) + { + if (!Path.GetExtension(filePath).Equals(".json", StringComparison.InvariantCultureIgnoreCase)) + goto EXIT_INVALID; + + if (!LocalizationLoader.TryGetCultureAndPrefixFromPath(filePath, out culture, out prefix)) + goto EXIT_INVALID; + + string fileName = Path.GetFileNameWithoutExtension(filePath); + if (fileName.StartsWith($"{prefix}_{DialogueFilePrefix}", StringComparison.InvariantCultureIgnoreCase)) + dialogueKey = fileName[$"{prefix}_{DialogueFilePrefix}".Length..]; + else if (fileName.StartsWith(DialogueFilePrefix, StringComparison.InvariantCultureIgnoreCase)) + dialogueKey = fileName[DialogueFilePrefix.Length..]; + else + goto EXIT_INVALID; + return true; + +EXIT_INVALID: + culture = null; + prefix = null; + dialogueKey = null; + return false; + } + + [GeneratedRegex(@".*?CalamityDialogue\..+?\.jsonc?$", RegexOptions.IgnoreCase)] + private static partial Regex CalamityDialogueFileRegex(); } diff --git a/Utilities/MainThreadedFileSystemWatcher.cs b/Utilities/MainThreadedFileSystemWatcher.cs new file mode 100644 index 0000000000..e282d84798 --- /dev/null +++ b/Utilities/MainThreadedFileSystemWatcher.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.ObjectModel; +using System.IO; +using System.Text.RegularExpressions; +using Terraria; + +namespace CalamityMod.Utilities +{ + internal sealed class MainThreadedFileSystemWatcher : IDisposable + { + public string Path + { + get => _FSW.Path; + set => _FSW.Path = value; + } + + public string Filter + { + get => _FSW.Filter; + set => _FSW.Filter = value; + } + + public Collection Filters + { + get => _FSW.Filters; + } + + public NotifyFilters NotifyFilter + { + get => _FSW.NotifyFilter; + set => _FSW.NotifyFilter = value; + } + + public bool IncludeSubdirectories + { + get => _FSW.IncludeSubdirectories; + set => _FSW.IncludeSubdirectories = value; + } + + public bool EnableRaisingEvents + { + get => _FSW.EnableRaisingEvents; + set => _FSW.EnableRaisingEvents = value; + } + + public Regex FileNameFilter { get; set; } = null; + + public event FileSystemEventHandler Changed; + public event RenamedEventHandler Renamed; + + public TimeSpan ChangedEventCooldown { get; set; } = TimeSpan.FromSeconds(0.1f); + public TimeSpan RenamedEventCooldown { get; set; } = TimeSpan.FromSeconds(0.1f); + + private FileSystemWatcher _FSW; + private DateTime _LastChangedEventDateTime = DateTime.Now; + private DateTime _LastRenamedEventDateTime = DateTime.Now; + private bool disposedValue; + + public MainThreadedFileSystemWatcher() + { + _FSW = new(); + _FSW.Changed += (o, arg) => + { + if (DateTime.Now - _LastChangedEventDateTime < ChangedEventCooldown) + return; + + if (!(FileNameFilter?.IsMatch(System.IO.Path.GetFileName(arg.Name)) ?? true)) + return; + + Main.QueueMainThreadAction(() => Changed?.Invoke(o, arg)); + _LastChangedEventDateTime = DateTime.Now; + }; + + _FSW.Renamed += (o, arg) => + { + if (DateTime.Now - _LastRenamedEventDateTime < RenamedEventCooldown) + return; + + if (!(FileNameFilter?.IsMatch(System.IO.Path.GetFileName(arg.Name)) ?? true)) + return; + + Main.QueueMainThreadAction(() => Renamed?.Invoke(o, arg)); + _LastRenamedEventDateTime = DateTime.Now; + }; + } + + private void Dispose(bool disposing) + { + if (!disposedValue) + { + if (disposing) + { + _FSW?.Dispose(); + } + + _FSW = null; + disposedValue = true; + } + } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + } +} From cf316dc2d32f7db2b0c13014fb612f8056859b6a Mon Sep 17 00:00:00 2001 From: Flowaria Date: Sat, 27 Dec 2025 16:09:21 +0900 Subject: [PATCH 40/53] Slight Readability Improvement --- Utilities/MainThreadedFileSystemWatcher.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Utilities/MainThreadedFileSystemWatcher.cs b/Utilities/MainThreadedFileSystemWatcher.cs index e282d84798..5d33eb88e6 100644 --- a/Utilities/MainThreadedFileSystemWatcher.cs +++ b/Utilities/MainThreadedFileSystemWatcher.cs @@ -61,10 +61,10 @@ namespace CalamityMod.Utilities _FSW = new(); _FSW.Changed += (o, arg) => { - if (DateTime.Now - _LastChangedEventDateTime < ChangedEventCooldown) + if ((DateTime.Now - _LastChangedEventDateTime) < ChangedEventCooldown) return; - if (!(FileNameFilter?.IsMatch(System.IO.Path.GetFileName(arg.Name)) ?? true)) + if (FileNameFilter != null && !FileNameFilter.IsMatch(System.IO.Path.GetFileName(arg.Name))) return; Main.QueueMainThreadAction(() => Changed?.Invoke(o, arg)); @@ -73,10 +73,10 @@ namespace CalamityMod.Utilities _FSW.Renamed += (o, arg) => { - if (DateTime.Now - _LastRenamedEventDateTime < RenamedEventCooldown) + if ((DateTime.Now - _LastRenamedEventDateTime) < RenamedEventCooldown) return; - if (!(FileNameFilter?.IsMatch(System.IO.Path.GetFileName(arg.Name)) ?? true)) + if (FileNameFilter != null && !FileNameFilter.IsMatch(System.IO.Path.GetFileName(arg.Name))) return; Main.QueueMainThreadAction(() => Renamed?.Invoke(o, arg)); From 3cb09e1f7dd0c5831338efe9c66ceb432fc03a90 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Sat, 27 Dec 2025 16:12:57 +0900 Subject: [PATCH 41/53] Slight Readability Improvement on TryGetDialogueFileInfo --- Dialogues/DialogueLoader.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs index 5a99510fef..634d059ec1 100644 --- a/Dialogues/DialogueLoader.cs +++ b/Dialogues/DialogueLoader.cs @@ -269,12 +269,15 @@ internal partial class DialogueLoader : ModSystem string fileName = Path.GetFileNameWithoutExtension(filePath); if (fileName.StartsWith($"{prefix}_{DialogueFilePrefix}", StringComparison.InvariantCultureIgnoreCase)) + { dialogueKey = fileName[$"{prefix}_{DialogueFilePrefix}".Length..]; + return true; + } else if (fileName.StartsWith(DialogueFilePrefix, StringComparison.InvariantCultureIgnoreCase)) + { dialogueKey = fileName[DialogueFilePrefix.Length..]; - else - goto EXIT_INVALID; - return true; + return true; + } EXIT_INVALID: culture = null; From 157a23c25a9708ecbe78d19979496b5a796c53f6 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Sat, 27 Dec 2025 20:47:45 +0900 Subject: [PATCH 42/53] Allow other mods to add their own Dialogue data --- Dialogues/DialogueLoader.cs | 76 ++++++++++++------- ...gue.CalamityMod.DevourerOfGods.Death.json} | 0 ...ogue.CalamityMod.DevourerOfGods.Head.json} | 0 ...ue.CalamityMod.DevourerOfGods.Phases.json} | 0 ...e.CalamityMod.DevourerOfGods.Running.json} | 0 NPCs/DevourerofGods/DevourerofGodsHead.cs | 6 +- 6 files changed, 51 insertions(+), 31 deletions(-) rename Dialogues/en-US/{CalamityDialogue.DevourerOfGods.Death.json => Dialogue.CalamityMod.DevourerOfGods.Death.json} (100%) rename Dialogues/en-US/{CalamityDialogue.DevourerOfGods.Head.json => Dialogue.CalamityMod.DevourerOfGods.Head.json} (100%) rename Dialogues/en-US/{CalamityDialogue.DevourerOfGods.Phases.json => Dialogue.CalamityMod.DevourerOfGods.Phases.json} (100%) rename Dialogues/en-US/{CalamityDialogue.DevourerOfGods.Running.json => Dialogue.CalamityMod.DevourerOfGods.Running.json} (100%) diff --git a/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs index 634d059ec1..14599593c7 100644 --- a/Dialogues/DialogueLoader.cs +++ b/Dialogues/DialogueLoader.cs @@ -26,7 +26,7 @@ internal record DialogueTextDataEntry( internal partial class DialogueLoader : ModSystem { - private const string DialogueFilePrefix = "CalamityDialogue."; + private const string DialogueFilePrefix = "Dialogue."; private static readonly Dictionary _DialogueLookup = []; private static readonly Dictionary _Watchers = []; @@ -123,10 +123,7 @@ internal partial class DialogueLoader : ModSystem cursor.EmitLdloc(pathLdloc); cursor.EmitDelegate((Mod mod, string basePath) => { - if (mod != CalamityMod.Instance) - return; - - foreach (var entry in GetDialogueTextDatas(CalamityMod.Instance, GameCulture.DefaultCulture, skipDeserializeData: true)) + foreach (var entry in GetDialogueTextEntries(mod, GameCulture.DefaultCulture, skipDeserializeData: true)) { try { @@ -134,7 +131,7 @@ internal partial class DialogueLoader : ModSystem var destDir = Path.GetDirectoryName(destFilePath); if (!Directory.Exists(destDir)) Directory.CreateDirectory(destDir); - using var stream = CalamityMod.Instance.File.GetStream(entry.FilePath); + using var stream = mod.File.GetStream(entry.FilePath); using var fileStream = File.OpenWrite(destFilePath); using var writer = new StreamWriter(fileStream, Encoding.UTF8); using var reader = new StreamReader(stream, Encoding.UTF8); @@ -142,7 +139,7 @@ internal partial class DialogueLoader : ModSystem } catch (Exception e) { - CalamityMod.Log.Error($"Error while exporting DialogueTextData entry ({CalamityMod.Instance}::{entry.FilePath}): {e}"); + CalamityMod.Log.Error($"Error while exporting DialogueTextData entry ({mod.Name}::{entry.FilePath}): {e}"); } } }); @@ -164,30 +161,48 @@ internal partial class DialogueLoader : ModSystem { _DialogueLookup.Clear(); - foreach (var entry in GetDialogueTextDatas(Mod, GameCulture.DefaultCulture)) + // Mods should be sorted by dependency order. + foreach (var entry in GetDialogueTextEntiresForAllMods(GameCulture.DefaultCulture)) { + if (_DialogueLookup.TryGetValue(entry.DialogueKey, out var oldEntry)) + { + if (entry.Data.Revision != oldEntry.Data.Revision) + { + CalamityMod.Log.Warn($"Dialogue Localization was detected but revision mismatches. This will not be applied! : '{entry.ProviderMod.Name}::{entry.FilePath}'"); + continue; + } + } + _DialogueLookup[entry.DialogueKey] = entry; } var activeCulture = LanguageManager.Instance.ActiveCulture; - foreach (var mod in ModLoader.Mods.Where(mod => mod != Mod)) + if (activeCulture == GameCulture.DefaultCulture) + return; + + foreach (var entry in GetDialogueTextEntiresForAllMods(activeCulture)) { - foreach (var entry in GetDialogueTextDatas(mod, activeCulture)) + var mod = entry.ProviderMod; + + if (!_DialogueLookup.TryGetValue(entry.DialogueKey, out var oldEntry)) { - if (!_DialogueLookup.TryGetValue(entry.DialogueKey, out var oldEntry)) - { - CalamityMod.Log.Warn($"Dialogue Localization was detected but original Dialogue file does not exists. This will not be applied! : '{mod.Name}::{entry.FilePath}'"); - continue; - } - - if (entry.Data.Revision != oldEntry.Data.Revision) - { - CalamityMod.Log.Warn($"Dialogue Localization was detected but revision mismatches. This will not be applied! : '{mod.Name}::{entry.FilePath}'"); - continue; - } - - _DialogueLookup[entry.DialogueKey] = entry; + CalamityMod.Log.Warn($"Dialogue Localization was detected but original Dialogue file does not exists. This will not be applied! : '{mod.Name}::{entry.FilePath}'"); + continue; } + + // Skip if entry is from same file. + if (oldEntry.ProviderMod == entry.ProviderMod && oldEntry.FilePath == entry.FilePath) + { + continue; + } + + if (oldEntry.Data.Revision != entry.Data.Revision) + { + CalamityMod.Log.Warn($"Dialogue Localization was detected but revision mismatches. This will not be applied! : '{mod.Name}::{entry.FilePath}'"); + continue; + } + + _DialogueLookup[entry.DialogueKey] = entry; } } @@ -220,7 +235,14 @@ internal partial class DialogueLoader : ModSystem } } - private static IEnumerable GetDialogueTextDatas(Mod mod, GameCulture targetCulture, bool skipDeserializeData = false) + private static IEnumerable GetDialogueTextEntiresForAllMods(GameCulture targetCulture, bool skipDeserializeData = false) + { + return ModLoader.Mods + .Where(mod => mod.File != null) + .SelectMany(mod => GetDialogueTextEntries(mod, targetCulture, skipDeserializeData)); + } + + private static IEnumerable GetDialogueTextEntries(Mod mod, GameCulture targetCulture, bool skipDeserializeData = false) { if (mod == null) yield break; @@ -233,9 +255,7 @@ internal partial class DialogueLoader : ModSystem if (!TryGetDialogueFileInfo(file.Name, out var culture, out var prefix, out var dialogueKey)) continue; - // Explictly Allow Default Culture File. - // This is for Translation mod that made for non-specified culture - if (culture != targetCulture && culture != GameCulture.DefaultCulture) + if (culture != targetCulture) continue; DialogueTextData data = null; @@ -286,6 +306,6 @@ EXIT_INVALID: return false; } - [GeneratedRegex(@".*?CalamityDialogue\..+?\.jsonc?$", RegexOptions.IgnoreCase)] + [GeneratedRegex(@"Dialogue\..+?\.jsonc?$", RegexOptions.IgnoreCase)] private static partial Regex CalamityDialogueFileRegex(); } diff --git a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Death.json b/Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Death.json similarity index 100% rename from Dialogues/en-US/CalamityDialogue.DevourerOfGods.Death.json rename to Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Death.json diff --git a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Head.json b/Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Head.json similarity index 100% rename from Dialogues/en-US/CalamityDialogue.DevourerOfGods.Head.json rename to Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Head.json diff --git a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Phases.json b/Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Phases.json similarity index 100% rename from Dialogues/en-US/CalamityDialogue.DevourerOfGods.Phases.json rename to Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Phases.json diff --git a/Dialogues/en-US/CalamityDialogue.DevourerOfGods.Running.json b/Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Running.json similarity index 100% rename from Dialogues/en-US/CalamityDialogue.DevourerOfGods.Running.json rename to Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Running.json diff --git a/NPCs/DevourerofGods/DevourerofGodsHead.cs b/NPCs/DevourerofGods/DevourerofGodsHead.cs index c0dd1c3eb5..8506089798 100644 --- a/NPCs/DevourerofGods/DevourerofGodsHead.cs +++ b/NPCs/DevourerofGods/DevourerofGodsHead.cs @@ -645,7 +645,7 @@ namespace CalamityMod.NPCs.DevourerofGods player.Calamity().subtitletext = Main.combatText[ctid]; player.Calamity().subtitleColors = new Color[] { Color.Cyan, Color.Fuchsia }; */ - DialogueDisplaySystem.StartDialogue("DevourerOfGods.Phases", NPC, 2, 120, false, new BossText()); + DialogueDisplaySystem.StartDialogue("CalamityMod.DevourerOfGods.Phases", NPC, 2, 120, false, new BossText()); } } @@ -822,7 +822,7 @@ namespace CalamityMod.NPCs.DevourerofGods player.Calamity().subtitletext = Main.combatText[ctid]; player.Calamity().subtitleColors = new Color[] { Color.Cyan, Color.Fuchsia }; */ - DialogueDisplaySystem.StartDialogue("DevourerOfGods.Phases", NPC, 3, 120, false, new BossText()); + DialogueDisplaySystem.StartDialogue("CalamityMod.DevourerOfGods.Phases", NPC, 3, 120, false, new BossText()); } spawnedGuardians3 = true; @@ -1485,7 +1485,7 @@ namespace CalamityMod.NPCs.DevourerofGods player.Calamity().subtitletext = Main.combatText[ctid]; player.Calamity().subtitleColors = new Color[] { Color.Cyan, Color.Fuchsia }; */ - DialogueDisplaySystem.StartDialogue("DevourerOfGods.Phases", NPC, 1, 120, false, new BossText()); + DialogueDisplaySystem.StartDialogue("CalamityMod.DevourerOfGods.Phases", NPC, 1, 120, false, new BossText()); } NPC.TargetClosest(); From e69b7ccf26a1148bcc82206ca32a2434d19f32b2 Mon Sep 17 00:00:00 2001 From: Cameron Ewell Date: Sun, 28 Dec 2025 12:35:54 -0500 Subject: [PATCH 43/53] DialogueData loader error message text fixes --- Dialogues/DialogueLoader.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs index 14599593c7..6cae3909ea 100644 --- a/Dialogues/DialogueLoader.cs +++ b/Dialogues/DialogueLoader.cs @@ -186,7 +186,7 @@ internal partial class DialogueLoader : ModSystem if (!_DialogueLookup.TryGetValue(entry.DialogueKey, out var oldEntry)) { - CalamityMod.Log.Warn($"Dialogue Localization was detected but original Dialogue file does not exists. This will not be applied! : '{mod.Name}::{entry.FilePath}'"); + CalamityMod.Log.Warn($"Dialogue Localization was detected but original Dialogue file does not exist. This will not be applied! : '{mod.Name}::{entry.FilePath}'"); continue; } @@ -225,7 +225,7 @@ internal partial class DialogueLoader : ModSystem Data = JsonSerializer.Deserialize(stream.BaseStream) }; - var hotreloadedMessage = $"Dialogue entry has hot reloaded: '{dialogueKey}', from source: '{filePath}'"; + var hotreloadedMessage = $"Dialogue entry has been hot reloaded: '{dialogueKey}', from source: '{filePath}'"; CalamityMod.Log.Info(hotreloadedMessage); if (!Main.gameMenu) Main.NewText(hotreloadedMessage); } From 9287475021cde94cf309d05660c448db594b0322 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Mon, 29 Dec 2025 18:22:35 +0900 Subject: [PATCH 44/53] Added Prefix: Mods to Dialogue Key --- ... => Dialogue.Mods.CalamityMod.DevourerOfGods.Death.json} | 0 ...n => Dialogue.Mods.CalamityMod.DevourerOfGods.Head.json} | 0 ...=> Dialogue.Mods.CalamityMod.DevourerOfGods.Phases.json} | 0 ...> Dialogue.Mods.CalamityMod.DevourerOfGods.Running.json} | 0 Items/SummonItems/CosmicWorm.cs | 1 + NPCs/DevourerofGods/DevourerofGodsHead.cs | 6 +++--- 6 files changed, 4 insertions(+), 3 deletions(-) rename Dialogues/en-US/{Dialogue.CalamityMod.DevourerOfGods.Death.json => Dialogue.Mods.CalamityMod.DevourerOfGods.Death.json} (100%) rename Dialogues/en-US/{Dialogue.CalamityMod.DevourerOfGods.Head.json => Dialogue.Mods.CalamityMod.DevourerOfGods.Head.json} (100%) rename Dialogues/en-US/{Dialogue.CalamityMod.DevourerOfGods.Phases.json => Dialogue.Mods.CalamityMod.DevourerOfGods.Phases.json} (100%) rename Dialogues/en-US/{Dialogue.CalamityMod.DevourerOfGods.Running.json => Dialogue.Mods.CalamityMod.DevourerOfGods.Running.json} (100%) diff --git a/Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Death.json b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Death.json similarity index 100% rename from Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Death.json rename to Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Death.json diff --git a/Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Head.json b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Head.json similarity index 100% rename from Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Head.json rename to Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Head.json diff --git a/Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Phases.json b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Phases.json similarity index 100% rename from Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Phases.json rename to Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Phases.json diff --git a/Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Running.json b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Running.json similarity index 100% rename from Dialogues/en-US/Dialogue.CalamityMod.DevourerOfGods.Running.json rename to Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Running.json diff --git a/Items/SummonItems/CosmicWorm.cs b/Items/SummonItems/CosmicWorm.cs index fc73ca9930..564311d0c5 100644 --- a/Items/SummonItems/CosmicWorm.cs +++ b/Items/SummonItems/CosmicWorm.cs @@ -49,6 +49,7 @@ namespace CalamityMod.Items.SummonItems NPC n = CalamityUtils.SpawnBossOnPosUsingItem(player, (int)player.Center.X, (int)player.Center.Y - 1600, DevourerofGodsHead.SpawnSound); + DialogueDisplaySystem.StartDialogue("Mods.CalamityMod.DevourerOfGods.Phases", n, 0, 120, false, new BossText()); return true; } diff --git a/NPCs/DevourerofGods/DevourerofGodsHead.cs b/NPCs/DevourerofGods/DevourerofGodsHead.cs index 8506089798..bdd9bee0be 100644 --- a/NPCs/DevourerofGods/DevourerofGodsHead.cs +++ b/NPCs/DevourerofGods/DevourerofGodsHead.cs @@ -645,7 +645,7 @@ namespace CalamityMod.NPCs.DevourerofGods player.Calamity().subtitletext = Main.combatText[ctid]; player.Calamity().subtitleColors = new Color[] { Color.Cyan, Color.Fuchsia }; */ - DialogueDisplaySystem.StartDialogue("CalamityMod.DevourerOfGods.Phases", NPC, 2, 120, false, new BossText()); + DialogueDisplaySystem.StartDialogue("Mods.CalamityMod.DevourerOfGods.Phases", NPC, 2, 120, false, new BossText()); } } @@ -822,7 +822,7 @@ namespace CalamityMod.NPCs.DevourerofGods player.Calamity().subtitletext = Main.combatText[ctid]; player.Calamity().subtitleColors = new Color[] { Color.Cyan, Color.Fuchsia }; */ - DialogueDisplaySystem.StartDialogue("CalamityMod.DevourerOfGods.Phases", NPC, 3, 120, false, new BossText()); + DialogueDisplaySystem.StartDialogue("Mods.CalamityMod.DevourerOfGods.Phases", NPC, 3, 120, false, new BossText()); } spawnedGuardians3 = true; @@ -1485,7 +1485,7 @@ namespace CalamityMod.NPCs.DevourerofGods player.Calamity().subtitletext = Main.combatText[ctid]; player.Calamity().subtitleColors = new Color[] { Color.Cyan, Color.Fuchsia }; */ - DialogueDisplaySystem.StartDialogue("CalamityMod.DevourerOfGods.Phases", NPC, 1, 120, false, new BossText()); + DialogueDisplaySystem.StartDialogue("Mods.CalamityMod.DevourerOfGods.Phases", NPC, 1, 120, false, new BossText()); } NPC.TargetClosest(); From 1097f264b7803159472fb313d1468ec94dc2c477 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Mon, 29 Dec 2025 18:44:47 +0900 Subject: [PATCH 45/53] Replace ILHook to MonoModHooks --- Dialogues/DialogueLoader.cs | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs index 6cae3909ea..40c32f8166 100644 --- a/Dialogues/DialogueLoader.cs +++ b/Dialogues/DialogueLoader.cs @@ -9,7 +9,6 @@ using System.Text.RegularExpressions; using CalamityMod.UI.DialogueDisplay; using CalamityMod.Utilities; using MonoMod.Cil; -using MonoMod.RuntimeDetour; using Terraria; using Terraria.Localization; using Terraria.ModLoader; @@ -31,8 +30,6 @@ internal partial class DialogueLoader : ModSystem private static readonly Dictionary _DialogueLookup = []; private static readonly Dictionary _Watchers = []; - private ILHook _ExtractLocalizationHook; - public override void Load() { _DialogueLookup.Clear(); @@ -40,8 +37,7 @@ internal partial class DialogueLoader : ModSystem var method = typeof(LocalizationLoader).GetMethod(nameof(LocalizationLoader.ExtractLocalizationFiles), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); if (method != null) { - _ExtractLocalizationHook = new ILHook(method, ExtractDialogueFilesPatch); - _ExtractLocalizationHook.Apply(); + MonoModHooks.Modify(method, ExtractDialogueFilesPatch); } } @@ -78,13 +74,6 @@ internal partial class DialogueLoader : ModSystem { _DialogueLookup.Clear(); - if (_ExtractLocalizationHook != null) - { - _ExtractLocalizationHook.Undo(); - _ExtractLocalizationHook.Dispose(); - _ExtractLocalizationHook = null; - } - foreach (var watcher in _Watchers.Values) { watcher.EnableRaisingEvents = false; From f645826a81ac7479378d8cb2de31e724a4bbeb02 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Mon, 29 Dec 2025 19:22:49 +0900 Subject: [PATCH 46/53] MainThreadedFSW - Remove Cooldown, Handle Event in form of Queue --- Dialogues/DialogueLoader.cs | 4 +- Utilities/MainThreadedFileSystemWatcher.cs | 230 ++++++++++++++------- 2 files changed, 152 insertions(+), 82 deletions(-) diff --git a/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs index 40c32f8166..4dd1c99f15 100644 --- a/Dialogues/DialogueLoader.cs +++ b/Dialogues/DialogueLoader.cs @@ -57,11 +57,11 @@ internal partial class DialogueLoader : ModSystem NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite, IncludeSubdirectories = true }; - watcher.Changed += (o, arg) => + watcher.Changed += (arg) => { HandleFileUpdate(mod, arg.FullPath); }; - watcher.Renamed += (o, arg) => + watcher.Renamed += (arg) => { HandleFileUpdate(mod, arg.FullPath); }; diff --git a/Utilities/MainThreadedFileSystemWatcher.cs b/Utilities/MainThreadedFileSystemWatcher.cs index 5d33eb88e6..c4e7a7c766 100644 --- a/Utilities/MainThreadedFileSystemWatcher.cs +++ b/Utilities/MainThreadedFileSystemWatcher.cs @@ -1,107 +1,177 @@ using System; +using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Text.RegularExpressions; using Terraria; +using Terraria.ModLoader; -namespace CalamityMod.Utilities +namespace CalamityMod.Utilities; + +internal sealed class MainThreadedFileSystemWatcher : IDisposable { - internal sealed class MainThreadedFileSystemWatcher : IDisposable + public string Path { - public string Path + get => _FSW.Path; + set => _FSW.Path = value; + } + + public string Filter + { + get => _FSW.Filter; + set => _FSW.Filter = value; + } + + public Collection Filters + { + get => _FSW.Filters; + } + + public NotifyFilters NotifyFilter + { + get => _FSW.NotifyFilter; + set => _FSW.NotifyFilter = value; + } + + public bool IncludeSubdirectories + { + get => _FSW.IncludeSubdirectories; + set => _FSW.IncludeSubdirectories = value; + } + + public bool EnableRaisingEvents + { + get => _FSW.EnableRaisingEvents; + set => _FSW.EnableRaisingEvents = value; + } + + public Regex FileNameFilter { get; set; } = null; + + public event Action Changed; + public event Action Renamed; + + private Dictionary _ChangedQueue = []; + private Dictionary _RenamedQueue = []; + + private FileSystemWatcher _FSW; + private bool _HasQueueInFrame = false; + private bool _Disposed; + + public MainThreadedFileSystemWatcher() + { + _FSW = new(); + _FSW.Changed += (o, arg) => { - get => _FSW.Path; - set => _FSW.Path = value; - } + if (FileNameFilter != null && !FileNameFilter.IsMatch(System.IO.Path.GetFileName(arg.Name))) + return; - public string Filter - { - get => _FSW.Filter; - set => _FSW.Filter = value; - } - - public Collection Filters - { - get => _FSW.Filters; - } - - public NotifyFilters NotifyFilter - { - get => _FSW.NotifyFilter; - set => _FSW.NotifyFilter = value; - } - - public bool IncludeSubdirectories - { - get => _FSW.IncludeSubdirectories; - set => _FSW.IncludeSubdirectories = value; - } - - public bool EnableRaisingEvents - { - get => _FSW.EnableRaisingEvents; - set => _FSW.EnableRaisingEvents = value; - } - - public Regex FileNameFilter { get; set; } = null; - - public event FileSystemEventHandler Changed; - public event RenamedEventHandler Renamed; - - public TimeSpan ChangedEventCooldown { get; set; } = TimeSpan.FromSeconds(0.1f); - public TimeSpan RenamedEventCooldown { get; set; } = TimeSpan.FromSeconds(0.1f); - - private FileSystemWatcher _FSW; - private DateTime _LastChangedEventDateTime = DateTime.Now; - private DateTime _LastRenamedEventDateTime = DateTime.Now; - private bool disposedValue; - - public MainThreadedFileSystemWatcher() - { - _FSW = new(); - _FSW.Changed += (o, arg) => + lock (_ChangedQueue) { - if ((DateTime.Now - _LastChangedEventDateTime) < ChangedEventCooldown) - return; + _ChangedQueue[arg.FullPath] = arg; + _HasQueueInFrame = true; + } + }; - if (FileNameFilter != null && !FileNameFilter.IsMatch(System.IO.Path.GetFileName(arg.Name))) - return; + _FSW.Renamed += (o, arg) => + { + if (FileNameFilter != null && !FileNameFilter.IsMatch(System.IO.Path.GetFileName(arg.Name))) + return; - Main.QueueMainThreadAction(() => Changed?.Invoke(o, arg)); - _LastChangedEventDateTime = DateTime.Now; - }; - - _FSW.Renamed += (o, arg) => + lock (_RenamedQueue) { - if ((DateTime.Now - _LastRenamedEventDateTime) < RenamedEventCooldown) - return; + _RenamedQueue[arg.FullPath] = arg; + _HasQueueInFrame = true; + } + }; - if (FileNameFilter != null && !FileNameFilter.IsMatch(System.IO.Path.GetFileName(arg.Name))) - return; + MainThreadedFileSystemWatcherSystem.Register(this); + } - Main.QueueMainThreadAction(() => Renamed?.Invoke(o, arg)); - _LastRenamedEventDateTime = DateTime.Now; - }; + private void Dispose(bool disposing) + { + if (!_Disposed) + { + if (disposing) + { + _FSW?.Dispose(); + } + + _FSW = null; + _Disposed = true; + _ChangedQueue?.Clear(); + _RenamedQueue?.Clear(); + _ChangedQueue = null; + _RenamedQueue = null; + _HasQueueInFrame = false; + MainThreadedFileSystemWatcherSystem.Unregister(this); + } + } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + private sealed class MainThreadedFileSystemWatcherSystem : ILoadable + { + private static MainThreadedFileSystemWatcher[] _Watchers = []; + private static HashSet _WatchersList = []; + + public static void Register(MainThreadedFileSystemWatcher watcher) + { + _WatchersList.Add(watcher); + _Watchers = [.. _WatchersList]; } - private void Dispose(bool disposing) + public static void Unregister(MainThreadedFileSystemWatcher watcher) { - if (!disposedValue) - { - if (disposing) - { - _FSW?.Dispose(); - } + _WatchersList.Remove(watcher); + _Watchers = [.. _WatchersList]; + } - _FSW = null; - disposedValue = true; + void ILoadable.Load(Mod mod) + { + Main.OnTickForThirdPartySoftwareOnly += Tick; + } + + void ILoadable.Unload() + { + Main.OnTickForThirdPartySoftwareOnly -= Tick; + } + + private void Tick() + { + foreach (var watcher in _Watchers) + { + if (!watcher._HasQueueInFrame) + continue; + + HandleQueuedEvents(watcher); } } - public void Dispose() + private static void HandleQueuedEvents(MainThreadedFileSystemWatcher watcher) { - Dispose(disposing: true); - GC.SuppressFinalize(this); + lock (watcher._ChangedQueue) + { + foreach (var changed in watcher._ChangedQueue.Values) + { + watcher.Changed?.Invoke(changed); + } + watcher._ChangedQueue.Clear(); + } + + lock (watcher._RenamedQueue) + { + foreach (var renamed in watcher._RenamedQueue.Values) + { + watcher.Renamed?.Invoke(renamed); + } + watcher._RenamedQueue.Clear(); + } + + watcher._HasQueueInFrame = false; } } } From b7af29b7ef74824d9ebe345e7cddcff8fdfb1f32 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Mon, 29 Dec 2025 19:28:25 +0900 Subject: [PATCH 47/53] Clear Watcher collection on Unload --- Utilities/MainThreadedFileSystemWatcher.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Utilities/MainThreadedFileSystemWatcher.cs b/Utilities/MainThreadedFileSystemWatcher.cs index c4e7a7c766..a605e9e674 100644 --- a/Utilities/MainThreadedFileSystemWatcher.cs +++ b/Utilities/MainThreadedFileSystemWatcher.cs @@ -138,6 +138,8 @@ internal sealed class MainThreadedFileSystemWatcher : IDisposable void ILoadable.Unload() { Main.OnTickForThirdPartySoftwareOnly -= Tick; + _WatchersList?.Clear(); + _Watchers = []; } private void Tick() From 2405d1c271b2b94baf71b0dba585767e4bbda841 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Mon, 29 Dec 2025 20:06:00 +0900 Subject: [PATCH 48/53] Added Proper SourceFolder check for FSW --- Dialogues/DialogueLoader.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs index 4dd1c99f15..60b906a873 100644 --- a/Dialogues/DialogueLoader.cs +++ b/Dialogues/DialogueLoader.cs @@ -12,7 +12,6 @@ using MonoMod.Cil; using Terraria; using Terraria.Localization; using Terraria.ModLoader; -using Terraria.ModLoader.Core; namespace CalamityMod.Dialogues; @@ -45,7 +44,10 @@ internal partial class DialogueLoader : ModSystem { foreach (var mod in ModLoader.Mods) { - string path = Path.Combine(ModCompile.ModSourcePath, mod.Name); + if (mod.File == null) + continue; + + var path = mod.SourceFolder; if (!Directory.Exists(path)) continue; From c89c0137010cdb8ecb9600ddd6a38afa2e60fa5e Mon Sep 17 00:00:00 2001 From: Flowaria Date: Tue, 30 Dec 2025 12:31:50 +0900 Subject: [PATCH 49/53] Removed Unused Usings --- UI/DialogueDisplay/DialogueDisplayUI.cs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/UI/DialogueDisplay/DialogueDisplayUI.cs b/UI/DialogueDisplay/DialogueDisplayUI.cs index 5739c68a8c..153eac8d15 100644 --- a/UI/DialogueDisplay/DialogueDisplayUI.cs +++ b/UI/DialogueDisplay/DialogueDisplayUI.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Net.Sockets; -using System.Text.Json; using System.Text.Json.Serialization; using CalamityMod.Dialogues; using CalamityMod.Packets; @@ -21,7 +19,6 @@ using Terraria.ID; using Terraria.ModLoader; using Terraria.UI; using Terraria.UI.Chat; -using static System.Runtime.InteropServices.JavaScript.JSType; using static CalamityMod.Packets.StartDialogueDisplayPacket; using static ReLogic.Graphics.DynamicSpriteFont; @@ -1124,8 +1121,8 @@ namespace CalamityMod.UI.DialogueDisplay if (Main.dedServ) return -1; - UI ??= new (); - State ??= new (); + UI ??= new(); + State ??= new(); effects ??= new DisplayEffect(); if (!DialogueLoader.TryGetDialogue(name, out var textData)) @@ -1144,9 +1141,9 @@ namespace CalamityMod.UI.DialogueDisplay }; int slot; - for (slot = 0; slot <= DialogueDisplayUI.Dialogues.Count; slot++) - if (!DialogueDisplayUI.Dialogues.ContainsKey(slot)) - break; + for (slot = 0; slot <= DialogueDisplayUI.Dialogues.Count; slot++) + if (!DialogueDisplayUI.Dialogues.ContainsKey(slot)) + break; DialogueDisplayUI.Dialogues.Add(slot, (name, display, textData, entity, Uptime)); From 6578b57dba6040138e2fcd50d7210a070626f6a4 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Tue, 30 Dec 2025 12:36:03 +0900 Subject: [PATCH 50/53] Removed BossText on CosmicWorm --- Items/SummonItems/CosmicWorm.cs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/Items/SummonItems/CosmicWorm.cs b/Items/SummonItems/CosmicWorm.cs index 564311d0c5..2c7bbb1321 100644 --- a/Items/SummonItems/CosmicWorm.cs +++ b/Items/SummonItems/CosmicWorm.cs @@ -2,12 +2,8 @@ using CalamityMod.Items.Materials; using CalamityMod.NPCs.DevourerofGods; using CalamityMod.Rarities; -using CalamityMod.UI.DialogueDisplay; -using CalamityMod.UI.DialogueDisplay.DisplayEffects; -using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; -using Terraria.Localization; using Terraria.ModLoader; namespace CalamityMod.Items.SummonItems @@ -48,8 +44,6 @@ namespace CalamityMod.Items.SummonItems return true; NPC n = CalamityUtils.SpawnBossOnPosUsingItem(player, (int)player.Center.X, (int)player.Center.Y - 1600, DevourerofGodsHead.SpawnSound); - - DialogueDisplaySystem.StartDialogue("Mods.CalamityMod.DevourerOfGods.Phases", n, 0, 120, false, new BossText()); return true; } From ca5f1d90b8768fc733c812f0789b815cb2eee901 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Tue, 30 Dec 2025 12:36:41 +0900 Subject: [PATCH 51/53] Updated Head spawn text key --- NPCs/DevourerofGods/DevourerofGodsHead.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/NPCs/DevourerofGods/DevourerofGodsHead.cs b/NPCs/DevourerofGods/DevourerofGodsHead.cs index bdd9bee0be..cd2714ad1d 100644 --- a/NPCs/DevourerofGods/DevourerofGodsHead.cs +++ b/NPCs/DevourerofGods/DevourerofGodsHead.cs @@ -4,7 +4,6 @@ using System.IO; using CalamityMod.Buffs.StatDebuffs; using CalamityMod.Dusts; using CalamityMod.Events; -using CalamityMod.Graphics.Renderers.CalamityRenderers; using CalamityMod.Items.Armor.Vanity; using CalamityMod.Items.LoreItems; using CalamityMod.Items.Materials; @@ -40,7 +39,6 @@ using Terraria.GameContent.Events; using Terraria.GameContent.ItemDropRules; using Terraria.Graphics.Shaders; using Terraria.ID; -using Terraria.Localization; using Terraria.ModLoader; namespace CalamityMod.NPCs.DevourerofGods @@ -312,7 +310,7 @@ namespace CalamityMod.NPCs.DevourerofGods Color messageColor = Color.Cyan; CalamityUtils.BroadcastLocalizedText(key, messageColor); - DialogueDisplaySystem.StartDialogue("DevourerOfGods.Phases", NPC, 0, 120, false, new BossText()); + DialogueDisplaySystem.StartDialogue("Mods.CalamityMod.DevourerOfGods.Phases", NPC, 0, 120, false, new BossText()); } public override void SendExtraAI(BinaryWriter writer) From c3f49f0165e810ff4e392576e5368397ea457e81 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Tue, 30 Dec 2025 13:27:14 +0900 Subject: [PATCH 52/53] Added Missing gameMenu check --- NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs index f3bb4594de..44d52c8a76 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs @@ -47,6 +47,9 @@ namespace CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses private static void DrawDeerclopsShadow() { + if (Main.gameMenu) + return; + bool shouldDraw; var deerclopsInactive = false; if (NPC.deerclopsBoss >= 0 && NPC.deerclopsBoss.WithinBounds(Main.npc.Length)) From 054016348ff65f8850d871c7f24422898bf719f3 Mon Sep 17 00:00:00 2001 From: Flowaria Date: Tue, 30 Dec 2025 13:25:08 +0900 Subject: [PATCH 53/53] Remove HolyInfernoRenderer --- .../CalamityRenderers/HolyInfernoRenderer.cs | 97 ------------------- NPCs/Providence/Providence.cs | 70 +++++++++++++ 2 files changed, 70 insertions(+), 97 deletions(-) delete mode 100644 Graphics/Renderers/CalamityRenderers/HolyInfernoRenderer.cs diff --git a/Graphics/Renderers/CalamityRenderers/HolyInfernoRenderer.cs b/Graphics/Renderers/CalamityRenderers/HolyInfernoRenderer.cs deleted file mode 100644 index 583d13f806..0000000000 --- a/Graphics/Renderers/CalamityRenderers/HolyInfernoRenderer.cs +++ /dev/null @@ -1,97 +0,0 @@ -using CalamityMod.Enums; -using CalamityMod.NPCs; -using CalamityMod.NPCs.Providence; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using Terraria; -using Terraria.GameContent; -using Terraria.Graphics.Shaders; -using Terraria.ModLoader; - -namespace CalamityMod.Graphics.Renderers.CalamityRenderers -{ - public class HolyInfernoRenderer : BaseRenderer - { - #region Fields/Properties - - public override GeneralDrawLayer Layer => GeneralDrawLayer.BeforeAllTiles; - - public static Providence Provi - { - get - { - if (!Main.npc.IndexInRange(CalamityGlobalNPC.holyBoss)) - return null; - if (Main.npc[CalamityGlobalNPC.holyBoss].type != ModContent.NPCType()) - return null; - - if (Main.npc[CalamityGlobalNPC.holyBoss].ModNPC is not null && - Main.npc[CalamityGlobalNPC.holyBoss].ModNPC is Providence provi) - return provi; - - return null; - } - } - - //Should only draw if not in the main menu, provi is active and the boolean for drawing the border is true. - public override bool ShouldDraw => !Main.gameMenu && CalamityGlobalNPC.holyBoss != -1 && - Main.npc[CalamityGlobalNPC.holyBoss].active && Providence.shouldDrawInfernoBorder; - #endregion - - #region Methods - public override void DrawToTarget(SpriteBatch spriteBatch) - { - var npc = Main.npc[CalamityGlobalNPC.holyBoss]; - var borderDistance = Providence.borderRadius; - if (!npc.HasValidTarget) - return; - - var target = Main.LocalPlayer; - var holyInfernoIntensity = target.Calamity().holyInfernoFadeIntensity; - var prov = Provi; - if (prov == null) - return; - - //Begin drawing the inferno - var blackTile = TextureAssets.MagicPixel; - var diagonalNoise = ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/HarshNoise"); - var upwardPerlinNoise = ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Perlin"); - var upwardNoise = ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/MeltyNoise"); - - var maxOpacity = 1f; - if (prov.Dying) - { - //Death animation timer ends at 345f. - maxOpacity = MathHelper.Lerp(1f, 0f, Utils.GetLerpValue(0f, 344f, prov.DeathAnimationTimer)); - } - - var shader = GameShaders.Misc["CalamityMod:HolyInfernoShader"].Shader; - shader.Parameters["colorMult"].SetValue(prov.hasBeenGivenFullPower ? 7.65f : 7.35f); //I want you to know it took considerable restraint to deliberately misspell colour. - shader.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly); - shader.Parameters["radius"].SetValue(borderDistance); - shader.Parameters["anchorPoint"].SetValue(npc.Center); - shader.Parameters["screenPosition"].SetValue(Main.screenPosition); - shader.Parameters["screenSize"].SetValue(Main.ScreenSize.ToVector2()); - shader.Parameters["burnIntensity"].SetValue(holyInfernoIntensity); - shader.Parameters["playerPosition"].SetValue(target.Center); - shader.Parameters["maxOpacity"].SetValue(maxOpacity); - shader.Parameters["day"].SetValue(!prov.hasBeenGivenFullPower); - - spriteBatch.GraphicsDevice.Textures[1] = diagonalNoise.Value; - spriteBatch.GraphicsDevice.Textures[2] = upwardNoise.Value; - spriteBatch.GraphicsDevice.Textures[3] = upwardPerlinNoise.Value; - - //Manual end begin for the sampler state - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, SamplerState.LinearWrap, DepthStencilState.None, Main.Rasterizer, shader, Main.Transform); - - Rectangle rekt = new(Main.screenWidth / 2, Main.screenHeight / 2, Main.screenWidth, Main.screenHeight); - spriteBatch.Draw(blackTile.Value, rekt, null, default, 0f, blackTile.Value.Size() * 0.5f, 0, 0f); - - //Inferno drawing complete - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise); - } - #endregion - } -} diff --git a/NPCs/Providence/Providence.cs b/NPCs/Providence/Providence.cs index 5cd463ed36..172e2d814e 100644 --- a/NPCs/Providence/Providence.cs +++ b/NPCs/Providence/Providence.cs @@ -28,6 +28,7 @@ using CalamityMod.Particles; using CalamityMod.Projectiles.Boss; using CalamityMod.Projectiles.Summon; using CalamityMod.Projectiles.Typeless; +using CalamityMod.Systems.Graphic; using CalamityMod.Tiles.Ores; using CalamityMod.Utilities.Daybreak; using CalamityMod.World; @@ -41,6 +42,7 @@ using Terraria.DataStructures; using Terraria.GameContent; using Terraria.GameContent.Bestiary; using Terraria.GameContent.ItemDropRules; +using Terraria.Graphics.Shaders; using Terraria.ID; using Terraria.Localization; using Terraria.ModLoader; @@ -249,6 +251,16 @@ namespace CalamityMod.NPCs.Providence public static int StarHeal = Main.expertMode ? 50 : 35; // HolyLight + public override void Load() + { + GeneralDrawLayerSystem.OnBeforeAllTiles += DrawHolyInferno; + } + + public override void Unload() + { + GeneralDrawLayerSystem.OnBeforeAllTiles -= DrawHolyInferno; + } + public override void SetDefaults() { NPC.npcSlots = 36f; @@ -2516,6 +2528,64 @@ namespace CalamityMod.NPCs.Providence } } + private static Asset DiagonalNoise => field ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/HarshNoise"); + private static Asset UpwardPerlinNoise => field ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Perlin"); + private static Asset UpwardNoise => field ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/MeltyNoise"); + + private static void DrawHolyInferno() + { + if (Main.gameMenu || !shouldDrawInfernoBorder) + return; + + if (CalamityGlobalNPC.holyBoss == -1) + return; + + var npc = Main.npc[CalamityGlobalNPC.holyBoss]; + var borderDistance = borderRadius; + if (!npc.active || !npc.HasValidTarget) + return; + + var target = Main.LocalPlayer; + var holyInfernoIntensity = target.Calamity().holyInfernoFadeIntensity; + var prov = npc.ModNPC(); + if (prov == null) + return; + + //Begin drawing the inferno + var blackTile = TextureAssets.MagicPixel; + + var maxOpacity = 1f; + if (prov.Dying) + { + //Death animation timer ends at 345f. + maxOpacity = MathHelper.Lerp(1f, 0f, Utils.GetLerpValue(0f, 344f, prov.DeathAnimationTimer)); + } + + var shader = GameShaders.Misc["CalamityMod:HolyInfernoShader"].Shader; + shader.Parameters["colorMult"].SetValue(prov.hasBeenGivenFullPower ? 7.65f : 7.35f); //I want you to know it took considerable restraint to deliberately misspell colour. + shader.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly); + shader.Parameters["radius"].SetValue(borderDistance); + shader.Parameters["anchorPoint"].SetValue(npc.Center); + shader.Parameters["screenPosition"].SetValue(Main.screenPosition); + shader.Parameters["screenSize"].SetValue(Main.ScreenSize.ToVector2()); + shader.Parameters["burnIntensity"].SetValue(holyInfernoIntensity); + shader.Parameters["playerPosition"].SetValue(target.Center); + shader.Parameters["maxOpacity"].SetValue(maxOpacity); + shader.Parameters["day"].SetValue(!prov.hasBeenGivenFullPower); + + Main.spriteBatch.GraphicsDevice.Textures[1] = DiagonalNoise.Value; + Main.spriteBatch.GraphicsDevice.Textures[2] = UpwardNoise.Value; + Main.spriteBatch.GraphicsDevice.Textures[3] = UpwardPerlinNoise.Value; + + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, SamplerState.LinearWrap, DepthStencilState.None, Main.Rasterizer, shader, Main.Transform); + + Rectangle rekt = new(Main.screenWidth / 2, Main.screenHeight / 2, Main.screenWidth, Main.screenHeight); + Main.spriteBatch.Draw(blackTile.Value, rekt, null, default, 0f, blackTile.Value.Size() * 0.5f, 0, 0f); + + //Inferno drawing complete + Main.spriteBatch.End(); + } + public override bool? DrawHealthBar(byte hbPosition, ref float scale, ref Vector2 position) { scale = 2f;