diff --git a/Backgrounds/SunkenSeaBurrowsBG.cs b/Backgrounds/SunkenSeaBurrowsBG.cs index 4c80584980..b8de0ce754 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() @@ -139,18 +140,19 @@ 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(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. + 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; } diff --git a/Buffs/DamageOverTime/MiracleBlight.cs b/Buffs/DamageOverTime/MiracleBlight.cs index bc2f149418..448b4616a7 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 (!CalamityDrawParameterNPC.DrawingMiracleBlight[npc.whoAmI]) + { + orig(self, iNPCIndex, behindTiles); + return; + } + + if (ExcludedNPCsForShader.Contains(npc.type)) + { + 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/Buffs/Summon/BrittleStar.png b/Buffs/Summon/BrittleStar.png index 3ae1924e0d..30f00daabc 100644 Binary files a/Buffs/Summon/BrittleStar.png and b/Buffs/Summon/BrittleStar.png differ diff --git a/CalPlayer/CalamityPlayer.cs b/CalPlayer/CalamityPlayer.cs index 98586c2db6..8d20d73e4d 100644 --- a/CalPlayer/CalamityPlayer.cs +++ b/CalPlayer/CalamityPlayer.cs @@ -963,8 +963,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; @@ -3392,7 +3390,6 @@ namespace CalamityMod.CalPlayer persecutedEnchantSummonTimer = 0; momentumCapacitorTime = 0; momentumCapacitorBoost = 0f; - vortexBoosterStealthDelay = 0; LungingDown = false; chaliceBleedoutBuffer = 0D; @@ -4480,6 +4477,7 @@ namespace CalamityMod.CalPlayer } #endregion + #region OnExtraJumpStarted public override void OnExtraJumpStarted(ExtraJump jump, ref bool playSound) { if (rainSet && Player.whoAmI == Main.myPlayer) @@ -4487,6 +4485,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/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/CalamityPlayerMiscEffects.cs b/CalPlayer/CalamityPlayerMiscEffects.cs index 9cc7b957fe..e421a926cd 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/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/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/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs new file mode 100644 index 0000000000..60b906a873 --- /dev/null +++ b/Dialogues/DialogueLoader.cs @@ -0,0 +1,302 @@ +using System; +using System.Collections.Generic; +using System.IO; +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 Terraria; +using Terraria.Localization; +using Terraria.ModLoader; + +namespace CalamityMod.Dialogues; + +internal record DialogueTextDataEntry( + Mod ProviderMod, + string FilePath, + string DialogueKey, + DialogueTextData Data + ); + +internal partial class DialogueLoader : ModSystem +{ + private const string DialogueFilePrefix = "Dialogue."; + + private static readonly Dictionary _DialogueLookup = []; + private static readonly Dictionary _Watchers = []; + + public override void Load() + { + _DialogueLookup.Clear(); + + var method = typeof(LocalizationLoader).GetMethod(nameof(LocalizationLoader.ExtractLocalizationFiles), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); + if (method != null) + { + MonoModHooks.Modify(method, ExtractDialogueFilesPatch); + } + } + + public override void PostSetupContent() + { + foreach (var mod in ModLoader.Mods) + { + if (mod.File == null) + continue; + + var path = mod.SourceFolder; + if (!Directory.Exists(path)) + continue; + + var watcher = new MainThreadedFileSystemWatcher() + { + Path = path, + Filter = "*.json", + FileNameFilter = CalamityDialogueFileRegex(), + NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite, + IncludeSubdirectories = true + }; + watcher.Changed += (arg) => + { + HandleFileUpdate(mod, arg.FullPath); + }; + watcher.Renamed += (arg) => + { + HandleFileUpdate(mod, arg.FullPath); + }; + watcher.EnableRaisingEvents = true; + _Watchers[mod] = watcher; + } + } + + public override void Unload() + { + _DialogueLookup.Clear(); + + foreach (var watcher in _Watchers.Values) + { + watcher.EnableRaisingEvents = false; + watcher.Dispose(); + } + + _Watchers.Clear(); + } + + 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 basePath) => + { + foreach (var entry in GetDialogueTextEntries(mod, 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 = 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); + writer.Write(reader.ReadToEnd()); + } + catch (Exception e) + { + CalamityMod.Log.Error($"Error while exporting DialogueTextData entry ({mod.Name}::{entry.FilePath}): {e}"); + } + } + }); + } + + public static bool TryGetDialogue(string dialogueKey, out DialogueTextData data) + { + if (_DialogueLookup.TryGetValue(dialogueKey, out var entry)) + { + data = entry.Data; + return true; + } + + data = null; + return false; + } + + public override void OnLocalizationsLoaded() + { + _DialogueLookup.Clear(); + + // 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; + if (activeCulture == GameCulture.DefaultCulture) + return; + + foreach (var entry in GetDialogueTextEntiresForAllMods(activeCulture)) + { + var mod = entry.ProviderMod; + + if (!_DialogueLookup.TryGetValue(entry.DialogueKey, out var oldEntry)) + { + CalamityMod.Log.Warn($"Dialogue Localization was detected but original Dialogue file does not exist. 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; + } + } + + 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 been 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 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; + + if (mod.File == null) + yield break; + + foreach (var file in mod.File) + { + if (!TryGetDialogueFileInfo(file.Name, out var culture, out var prefix, out var dialogueKey)) + continue; + + if (culture != targetCulture) + continue; + + DialogueTextData data = null; + if (!skipDeserializeData) + { + 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 ({mod.Name}::{file.Name}): {e}"); + } + } + + if (data != null || skipDeserializeData) + { + 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..]; + return true; + } + else if (fileName.StartsWith(DialogueFilePrefix, StringComparison.InvariantCultureIgnoreCase)) + { + dialogueKey = fileName[DialogueFilePrefix.Length..]; + return true; + } + +EXIT_INVALID: + culture = null; + prefix = null; + dialogueKey = null; + return false; + } + + [GeneratedRegex(@"Dialogue\..+?\.jsonc?$", RegexOptions.IgnoreCase)] + private static partial Regex CalamityDialogueFileRegex(); +} diff --git a/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Death.json b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Death.json new file mode 100644 index 0000000000..3e92c78a0f --- /dev/null +++ b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Death.json @@ -0,0 +1,54 @@ +{ + "Revision": 1, + "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/Dialogue.Mods.CalamityMod.DevourerOfGods.Head.json b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Head.json new file mode 100644 index 0000000000..93da2b43ff --- /dev/null +++ b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Head.json @@ -0,0 +1,95 @@ +{ + "Revision": 1, + "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/Dialogue.Mods.CalamityMod.DevourerOfGods.Phases.json b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Phases.json new file mode 100644 index 0000000000..3ae52d8b17 --- /dev/null +++ b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Phases.json @@ -0,0 +1,48 @@ +{ + "Revision": 1, + "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/Dialogue.Mods.CalamityMod.DevourerOfGods.Running.json b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Running.json new file mode 100644 index 0000000000..de35cd7052 --- /dev/null +++ b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Running.json @@ -0,0 +1,37 @@ +{ + "Revision": 1, + "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/FluidSimulation/FluidField.cs b/FluidSimulation/FluidField.cs index 465a2f9de7..213307ced2 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,31 +86,31 @@ 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) { - 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); + 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,9 +167,9 @@ 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; + 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); @@ -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); @@ -202,16 +202,15 @@ 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++) { - ApplyThingToTarget(DivergencePoissonField, () => + ApplyThingToTarget(DivergencePoissonField.Target, () => { - 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 +219,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(); }); } @@ -255,36 +254,34 @@ 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() { - 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; - 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.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() @@ -321,9 +318,9 @@ 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, 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 3036565049..0e9da15fbb 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(); @@ -20,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) @@ -31,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/ManagedRenderTarget.cs b/Graphics/ManagedRenderTarget.cs index f69b815ca7..47f563979f 100644 --- a/Graphics/ManagedRenderTarget.cs +++ b/Graphics/ManagedRenderTarget.cs @@ -1,114 +1,138 @@ 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. - /// - 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 bool WaitingForFirstInitialization + public void Return(ManagedRenderTarget managedRt, bool preserveCollection) + { + if (!preserveCollection) { - get; - private set; - } = true; - - public bool IsUninitialized => target is null || target.IsDisposed; - - public bool IsDisposed - { - get; - private set; + _ = managedTargets.Remove(managedRt); } - /// - /// The actual instance that the wrapper contains. - /// - public RenderTarget2D Target + Return(managedRt.lease); + } + + public override void Dispose() + { + foreach (var target in managedTargets) { - get + target.Dispose(preserveCollection: true); + } + + managedTargets.Clear(); + } + + internal void ResizeTargets() + { + foreach (var target in managedTargets) + { + 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() + { + Dispose(preserveCollection: false); + } + + public void Dispose(bool preserveCollection) + { + if (IsDisposed) + return; + + IsDisposed = true; + ManagedRenderTargetPool.Shared.Return(this, preserveCollection); + } + + // Does nothing + public void Recreate(int screenWidth, int screenHeight) { } + + public static implicit operator RenderTarget2D(ManagedRenderTarget target) => target.Target; +} 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/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..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; @@ -70,20 +71,19 @@ 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); - 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(); } @@ -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/Primitives/PrimitivePixelationSystem.cs b/Graphics/Primitives/PrimitivePixelationSystem.cs index 3fa1d49fbc..582591c4a0 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; @@ -156,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; } @@ -174,16 +171,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(clearColor: Color.Transparent)) { - 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 @@ -200,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/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/Graphics/Renderers/BaseRenderer.cs b/Graphics/Renderers/BaseRenderer.cs index cb1e3dc5a8..99e1994015 100644 --- a/Graphics/Renderers/BaseRenderer.cs +++ b/Graphics/Renderers/BaseRenderer.cs @@ -1,80 +1,88 @@ using System; using CalamityMod.Enums; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; 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 ManagedRenderTarget 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() => MainTarget = new(true, ManagedRenderTarget.CreateScreenSizedTarget); - - /// - /// 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, 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 } 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/Graphics/Renderers/CalamityRenderers/DoGDeathAnimationRenderer.cs b/Graphics/Renderers/CalamityRenderers/DoGDeathAnimationRenderer.cs deleted file mode 100644 index 8dd595233c..0000000000 --- a/Graphics/Renderers/CalamityRenderers/DoGDeathAnimationRenderer.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using CalamityMod.Enums; -using CalamityMod.NPCs; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using ReLogic.Content; -using Terraria; -using Terraria.Graphics.Shaders; -using Terraria.ID; -using Terraria.ModLoader; - -namespace CalamityMod.Graphics.Renderers.CalamityRenderers -{ - public class DoGDeathAnimationRenderer : BaseRenderer - { - /// - /// 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; - - public override bool ShouldDraw => false;//!Main.gameMenu && CalamityDrawParameterNPC.DoGDeathAnimationTimer > 0; - - public static bool ValidToDraw(NPC npc) - { - return false; - /* - // 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.DrawingDoGDeathAnimation[npc.whoAmI]) - return false; - - return true; - */ - } - - public override void DrawToTarget(SpriteBatch spriteBatch) - { - // Indicate that DoG and his segments should draw. - ActuallyDoPreDraw = true; - - // Draw every npc to a single target that should have the disintegration 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; - - // Draw the NPCs to the target once everything is valid and set the disintegration progress variable. - // Also ensure to indicate that the renderer should allow drawing the target here as well. - if (ValidToDraw(npc)) - Main.instance.DrawNPC(npc.whoAmI, npc.behindTiles); - } - - // Indicate that DoG and his segments should no longer draw. - ActuallyDoPreDraw = false; - } - - public override void DrawTarget(SpriteBatch spriteBatch) - { - - spriteBatch.Draw(MainTarget, Vector2.Zero, Color.White); - - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise); - } - } -} diff --git a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs index 799922dd00..60479a2908 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. @@ -164,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(clearColor: Color.Transparent)) + { + renderer.DrawDyeableShader(spriteBatch); + } } } @@ -188,10 +191,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/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/Graphics/Renderers/CalamityRenderers/MiracleBlightRenderer.cs b/Graphics/Renderers/CalamityRenderers/MiracleBlightRenderer.cs deleted file mode 100644 index 330a07e939..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, Vector2.Zero, Color.White); - - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise); - } - #endregion - } -} 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/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/ILEditing/MechanicILChanges.cs b/ILEditing/MechanicILChanges.cs index d8c16eea1e..7ec6f38150 100644 --- a/ILEditing/MechanicILChanges.cs +++ b/ILEditing/MechanicILChanges.cs @@ -1153,7 +1153,7 @@ namespace CalamityMod.ILEditing orig(self, drawData, solidLayer, waterStyleOverride, screenPosition, screenOffset, tileX, tileY); var type = drawData.typeCache; - if (type < 0 || type >= GlowMaskTile.LookupLength) + if (type >= GlowMaskTile.LookupLength) return; var glowMaskTile = GlowMaskTile.InstanceLookup[type]; diff --git a/Items/Accessories/Wings/MOAB.cs b/Items/Accessories/Wings/MOAB.cs index 997d77ee74..4603a286db 100644 --- a/Items/Accessories/Wings/MOAB.cs +++ b/Items/Accessories/Wings/MOAB.cs @@ -22,6 +22,9 @@ namespace CalamityMod.Items.Accessories.Wings public override float BaseAscent => 0.125f; public static int wingSlot = 0; + // How powerful the acceleration increase is while pressing UP + // This also affects the flight time tick rate + public static float BoostPower = 2f; public override void SetStaticDefaults() { ArmorIDs.Wing.Sets.Stats[Item.wingSlot] = new WingStats(75, 6.5f, 1f); @@ -153,6 +156,20 @@ namespace CalamityMod.Items.Accessories.Wings // Mirrors the +5% luck from Lucky Horseshoe (vanilla behavior). player.Calamity().calamityBonusLuck += 0.05f; } + + public override void AdditionalFlightMovement(Player player, ref float ascentWhenFalling, ref float ascentWhenRising, ref float maxCanAscendMultiplier, ref float maxAscentMultiplier, ref float constantAscend) + { + if (player.TryingToHoverUp) + { + ascentWhenFalling *= BoostPower; + ascentWhenRising *= BoostPower; + maxCanAscendMultiplier *= BoostPower; + maxAscentMultiplier *= BoostPower; + constantAscend *= BoostPower; + player.wingTime -= BoostPower - 1f; + } + } + public override void AddRecipes() { CreateRecipe(). 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/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 0000000000..a8627f069b Binary files /dev/null and b/Items/Placeables/Furniture/Paintings/ForgivenessPainting.png differ diff --git a/Items/SummonItems/CosmicWorm.cs b/Items/SummonItems/CosmicWorm.cs index cc2aa24914..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 @@ -47,23 +43,7 @@ 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/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; diff --git a/Items/Weapons/Magic/SandstreamScepter.png b/Items/Weapons/Magic/SandstreamScepter.png index 64e58ebf01..c85eec12d1 100644 Binary files a/Items/Weapons/Magic/SandstreamScepter.png and b/Items/Weapons/Magic/SandstreamScepter.png differ diff --git a/Items/Weapons/Melee/SaharaSlicers.png b/Items/Weapons/Melee/SaharaSlicers.png index d3667f574b..aecbe93345 100644 Binary files a/Items/Weapons/Melee/SaharaSlicers.png and b/Items/Weapons/Melee/SaharaSlicers.png differ diff --git a/Items/Weapons/Ranged/Barinade.png b/Items/Weapons/Ranged/Barinade.png index 5ab49d1c58..0d4a6b1bf8 100644 Binary files a/Items/Weapons/Ranged/Barinade.png and b/Items/Weapons/Ranged/Barinade.png differ diff --git a/Items/Weapons/Ranged/OntologicalDespoiler.cs b/Items/Weapons/Ranged/OntologicalDespoiler.cs index 40fc8c33f2..9230171e4d 100644 --- a/Items/Weapons/Ranged/OntologicalDespoiler.cs +++ b/Items/Weapons/Ranged/OntologicalDespoiler.cs @@ -68,12 +68,15 @@ namespace CalamityMod.Items.Weapons.Ranged // 14NOV2024: Ozzatron: clamped mouse position unnecessary, only used for direction - if (player.Calamity().mouseRight && player.whoAmI == Main.myPlayer && !Main.mapFullscreen && !Main.blockMouse && player.Calamity().despoilerNerf) + if (player.Calamity().mouseRight && player.whoAmI == Main.myPlayer && !Main.mapFullscreen && !Main.blockMouse) { - Projectile holdout2 = Projectile.NewProjectileDirect(source, player.Center, Vector2.Zero, Item.shoot, player.HeldItem.damage, 0f, player.whoAmI, 0, 0, 10 + (shotType ? 5 : 0)); + int aiType = 10 + (shotType ? 5 : 0); + if (!player.Calamity().despoilerNerf) + aiType = 20; + Projectile holdout2 = Projectile.NewProjectileDirect(source, player.Center, Vector2.Zero, Item.shoot, player.HeldItem.damage, 0f, player.whoAmI, 0, 0, aiType); holdout2.velocity = (player.Calamity().mouseWorld - player.MountedCenter).SafeNormalize(Vector2.Zero); SoundStyle fire = new("CalamityMod/Sounds/Item/DudFire"); - SoundEngine.PlaySound(fire with { Volume = 0.7f, Pitch = -0.5f + (shotType ? 0.5f : 0) }, player.Center); + SoundEngine.PlaySound(fire with { Volume = 0.7f, Pitch = aiType == 20 ? -0.7f : (-0.5f + (shotType ? 0.5f : 0)) }, player.Center); shotType = !shotType; } else diff --git a/Items/Weapons/Rogue/ScourgeoftheDesert.png b/Items/Weapons/Rogue/ScourgeoftheDesert.png index 625d9bb541..8e86310af5 100644 Binary files a/Items/Weapons/Rogue/ScourgeoftheDesert.png and b/Items/Weapons/Rogue/ScourgeoftheDesert.png differ diff --git a/Items/Weapons/Rogue/Vega.cs b/Items/Weapons/Rogue/Vega.cs index 7b5832a40d..3adbc2e852 100644 --- a/Items/Weapons/Rogue/Vega.cs +++ b/Items/Weapons/Rogue/Vega.cs @@ -12,7 +12,7 @@ using Terraria.ModLoader; namespace CalamityMod.Items.Weapons.Rogue { [LegacyName("NightsGaze")] - public class Vega : RogueWeapon, IHoldShiftTooltipItem + public class Vega : RogueWeapon { public static int StarburstCost = 20; public override void SetDefaults() diff --git a/Items/Weapons/Summon/BrittleStarStaff.png b/Items/Weapons/Summon/BrittleStarStaff.png index 5bcb654ee5..782d3eb149 100644 Binary files a/Items/Weapons/Summon/BrittleStarStaff.png and b/Items/Weapons/Summon/BrittleStarStaff.png differ 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/Localization/en-US/Mods.CalamityMod.Items.Accessories.Wings.hjson b/Localization/en-US/Mods.CalamityMod.Items.Accessories.Wings.hjson index c39f19ab3a..100e290574 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Accessories.Wings.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Accessories.Wings.hjson @@ -51,6 +51,7 @@ MOAB: { Tooltip: ''' {$CommonItemTooltip.FlightAndSlowfall} + {$CommonItemTooltip.PressUpToBooster} 32% increased jump speed and allows auto-jump Grants the player cloud, blizzard, and sandstorm mid-air jumps [c/aaaaaa:Shift- this item in your inventory to toggle the] [i:Jetpack] [c/aaaaaa:jetpack] diff --git a/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson b/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson index 8dff78f9bc..8748849c61 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/Localization/en-US/Mods.CalamityMod.Items.Weapons.Ranged.hjson b/Localization/en-US/Mods.CalamityMod.Items.Weapons.Ranged.hjson index 9fb901f267..95f3fc4b08 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Weapons.Ranged.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Weapons.Ranged.hjson @@ -813,7 +813,7 @@ OntologicalDespoiler: { DisplayName: Ontological Despoiler Tooltip: ''' - Condenses chargeable pockets of concentrated unreality. to swap modes + Condenses chargeable pockets of concentrated unreality. to swap modes only after firing a charged shot Unstable condensate shots trifurcate and pierce enemies Null condensate shots fire rapidly and home in on enemies At 50% charge or higher, rate of fire significantly increases 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/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 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/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/NPCs/CalClone/CalamitasClone.cs b/NPCs/CalClone/CalamitasClone.cs index 5fbdc3097a..b0c44f9306 100644 --- a/NPCs/CalClone/CalamitasClone.cs +++ b/NPCs/CalClone/CalamitasClone.cs @@ -165,7 +165,6 @@ namespace CalamityMod.NPCs.CalClone writer.Write(NPC.localAI[0]); writer.Write(NPC.localAI[1]); writer.Write(NPC.localAI[2]); - writer.Write(NPC.localAI[3]); for (int i = 0; i < 4; i++) writer.Write(NPC.Calamity().newAI[i]); } @@ -176,7 +175,6 @@ namespace CalamityMod.NPCs.CalClone NPC.localAI[0] = reader.ReadSingle(); NPC.localAI[1] = reader.ReadSingle(); NPC.localAI[2] = reader.ReadSingle(); - NPC.localAI[3] = reader.ReadSingle(); for (int i = 0; i < 4; i++) NPC.Calamity().newAI[i] = reader.ReadSingle(); } @@ -499,16 +497,17 @@ namespace CalamityMod.NPCs.CalClone if (NPC.localAI[0] == 1f) { NPC.localAI[0] = 0f; - NPC.localAI[2] = Main.rand.Next(-50, 51); - NPC.localAI[3] = Main.rand.Next(-300, 301); + NPC.localAI[2] = Main.rand.Next(-300, 301); NPC.netUpdate = true; } // Add a bit of randomness to the destination if (death) { - destination.X += NPC.ai[1] == 0f ? NPC.localAI[3] : NPC.localAI[2]; - destination.Y += NPC.ai[1] == 0f ? NPC.localAI[2] : NPC.localAI[3]; + if (NPC.ai[1] == 0f) + destination.X += NPC.localAI[2]; + else + destination.Y += NPC.localAI[2]; } // How far Cal Clone is from where she's supposed to be diff --git a/NPCs/CalamityDrawParameterNPC.cs b/NPCs/CalamityDrawParameterNPC.cs index 91fd106261..bf4d15ddbe 100644 --- a/NPCs/CalamityDrawParameterNPC.cs +++ b/NPCs/CalamityDrawParameterNPC.cs @@ -16,7 +16,6 @@ namespace CalamityMod.NPCs #region Draw Parameters public static bool[] DrawingMiracleBlight { get; private set; } public static bool[] DrawingPolarity { get; private set; } - public static bool[] DrawingDoGDeathAnimation { get; private set; } public static int DoGDeathAnimationTimer { get; private set; } #endregion @@ -44,14 +43,12 @@ namespace CalamityMod.NPCs { DrawingMiracleBlight = new bool[Main.maxNPCs + 1]; DrawingPolarity = new bool[Main.maxNPCs + 1]; - DrawingDoGDeathAnimation = new bool[Main.maxNPCs + 1]; } public override void Unload() { DrawingMiracleBlight = null; DrawingPolarity = null; - DrawingDoGDeathAnimation = null; } #endregion @@ -67,7 +64,6 @@ namespace CalamityMod.NPCs var whoAmI = npc.whoAmI; DrawingMiracleBlight[whoAmI] = false; DrawingPolarity[whoAmI] = false; - DrawingDoGDeathAnimation[whoAmI] = false; } public override bool PreAI(NPC npc) @@ -81,7 +77,6 @@ namespace CalamityMod.NPCs var whoAmI = npc.whoAmI; DrawingMiracleBlight[whoAmI] = ShouldDrawMiracleBlight(npc); DrawingPolarity[whoAmI] = ShouldDrawPolarity(npc); - DrawingDoGDeathAnimation[whoAmI] = ShouldDrawDoGDeathAnimation(npc); return true; } diff --git a/NPCs/CalamityGlobalNPC.cs b/NPCs/CalamityGlobalNPC.cs index 1c16de3fac..5cf1a9e0e6 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; @@ -1271,112 +1270,150 @@ namespace CalamityMod.NPCs #region Revengeance and Death Mode Stat Changes private void RevDeathStatChanges(NPC npc, Mod mod) { + // Health changes (disabled in Boss Rush) + if (!BossRushEvent.BossRushActive) + { + switch (npc.type) + { + case NPCID.KingSlime: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.5); + break; + case NPCID.EyeofCthulhu: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.5); + break; + case NPCID.ServantofCthulhu: + npc.lifeMax *= 4; + break; + case NPCID.BrainofCthulhu: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.75); + break; + case NPCID.Creeper: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.1); + break; + case NPCID.QueenBee: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.8); + break; + case NPCID.Bee: + case NPCID.BeeSmall: + if (CalamityPlayer.areThereAnyDamnBosses) + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.5); + break; + case NPCID.Deerclops: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.4); + break; + case NPCID.SkeletronHand: + npc.lifeMax = (int)Math.Round(npc.lifeMax * (CalamityWorld.death ? 0.5 : 0.75)); + break; + case NPCID.WallofFlesh: + case NPCID.WallofFleshEye: + npc.lifeMax *= 2; + break; + case NPCID.QueenSlimeBoss: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.8); + break; + case NPCID.Retinazer: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.4); + break; + case NPCID.Spazmatism: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.3); + break; + case NPCID.Probe: + if (CalamityWorld.death) + npc.lifeMax *= 2; + break; + case NPCID.SkeletronPrime: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.2); + break; + case NPCID.PrimeCannon: + case NPCID.PrimeSaw: + case NPCID.PrimeVice: + case NPCID.PrimeLaser: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 0.65); + break; + case NPCID.Plantera: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 2.85); + break; + case NPCID.PlanterasTentacle: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 0.5); + break; + case NPCID.Golem: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 3.2); + break; + case NPCID.GolemHead: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.28); + break; + case NPCID.GolemFistLeft: + case NPCID.GolemFistRight: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 0.75); + break; + case NPCID.DukeFishron: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 2.3); + break; + case NPCID.Sharkron: + case NPCID.Sharkron2: + npc.lifeMax *= 5; + break; + case NPCID.HallowBoss: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.7); + break; + case NPCID.CultistBoss: + npc.lifeMax *= 3; + break; + case NPCID.AncientCultistSquidhead: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.8); + break; + case NPCID.MoonLordCore: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 2.2); + break; + case NPCID.MoonLordHand: + case NPCID.MoonLordHead: + case NPCID.MoonLordLeechBlob: + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.2); + break; + } + + if (npc.type >= NPCID.CultistDragonHead && npc.type <= NPCID.CultistDragonTail) + { + npc.lifeMax = (int)Math.Round(npc.lifeMax * 2.4); + } + else if (CalamityNPCTypeSets.Destroyer.Contains(npc.type)) + { + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.25); + } + else if (CalamityNPCTypeSets.EaterOfWorlds.Contains(npc.type)) + { + npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.4); + } + } + + // Other stat changes switch (npc.type) { case NPCID.KingSlime: npc.scale = CalamityWorld.death ? (Main.getGoodWorld ? 6f : 2.5f) : (Main.getGoodWorld ? 3f : 1.5f); - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.5); - break; - case NPCID.EyeofCthulhu: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.5); - break; - case NPCID.ServantofCthulhu: - npc.lifeMax *= 4; - break; - case NPCID.BrainofCthulhu: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.75); - break; - case NPCID.Creeper: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.1); break; case NPCID.QueenBee: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.8); npc.defense = 14; npc.defDefense = npc.defense; break; case NPCID.Bee: case NPCID.BeeSmall: if (CalamityPlayer.areThereAnyDamnBosses) - { - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.5); npc.scale *= 1.25f; - } - break; - case NPCID.Deerclops: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.4); - break; - case NPCID.SkeletronHand: - npc.lifeMax = (int)Math.Round(npc.lifeMax * (CalamityWorld.death ? 0.5 : 0.75)); - break; - case NPCID.WallofFlesh: - case NPCID.WallofFleshEye: - npc.lifeMax *= 2; - break; - case NPCID.QueenSlimeBoss: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.8); - break; - case NPCID.Retinazer: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.4); - break; - case NPCID.Spazmatism: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.3); break; case NPCID.Probe: - if (CalamityWorld.death) - npc.lifeMax *= 2; npc.scale *= Main.zenithWorld ? 2f : 1.2f; break; - case NPCID.SkeletronPrime: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.2); - break; case NPCID.PrimeCannon: case NPCID.PrimeSaw: case NPCID.PrimeVice: case NPCID.PrimeLaser: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 0.65); npc.scale *= 1.15f; break; - case NPCID.Plantera: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 2.85); - break; - case NPCID.PlanterasTentacle: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 0.5); - break; - case NPCID.Golem: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 3.2); - break; - case NPCID.GolemHead: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.28); - break; case NPCID.GolemFistLeft: case NPCID.GolemFistRight: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 0.75); npc.scale *= 1.15f; break; - case NPCID.DukeFishron: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 2.3); - break; - case NPCID.Sharkron: - case NPCID.Sharkron2: - npc.lifeMax *= 5; - break; - case NPCID.HallowBoss: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.7); - break; - case NPCID.CultistBoss: - npc.lifeMax *= 3; - break; - case NPCID.AncientCultistSquidhead: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.8); - break; - case NPCID.MoonLordCore: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 2.2); - break; - case NPCID.MoonLordHand: - case NPCID.MoonLordHead: - case NPCID.MoonLordLeechBlob: - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.2); - break; case NPCID.Mothron: npc.scale *= 1.25f; break; @@ -1392,18 +1429,12 @@ namespace CalamityMod.NPCs break; } - if (npc.type >= NPCID.CultistDragonHead && npc.type <= NPCID.CultistDragonTail) + if (CalamityNPCTypeSets.Destroyer.Contains(npc.type)) { - npc.lifeMax = (int)Math.Round(npc.lifeMax * 2.4); - } - else if (CalamityNPCTypeSets.Destroyer.Contains(npc.type)) - { - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.25); npc.scale *= Main.zenithWorld ? 2f : 1.2f; } else if (CalamityNPCTypeSets.EaterOfWorlds.Contains(npc.type)) { - npc.lifeMax = (int)Math.Round(npc.lifeMax * 1.4); if (CalamityWorld.death) npc.scale *= 1.1f; } @@ -2447,12 +2478,6 @@ namespace CalamityMod.NPCs npc.chaseable = false; break; - // Fix drawing issues with Golem's Free Head - case NPCID.GolemHeadFree: - npc.width = 88; - npc.height = 90; - break; - // Make Core hitbox bigger case NPCID.MartianSaucerCore: npc.width *= 2; @@ -5386,14 +5411,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; - - // Only draw DoG's death animation when told to by the renderer. - if (DoGDeathAnimationRenderer.ValidToDraw(npc)) - return DoGDeathAnimationRenderer.ActuallyDoPreDraw; } if (Main.zenithWorld) diff --git a/NPCs/CalamityGlobalTownNPC.cs b/NPCs/CalamityGlobalTownNPC.cs index b7d9a200e4..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"); } @@ -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/NPCs/CalamityVanillaAIOverrideNPC.cs b/NPCs/CalamityVanillaAIOverrideNPC.cs index ce84672cf7..353c355c11 100644 --- a/NPCs/CalamityVanillaAIOverrideNPC.cs +++ b/NPCs/CalamityVanillaAIOverrideNPC.cs @@ -11,6 +11,7 @@ using CalamityMod.NPCs.PlagueEnemies; using CalamityMod.NPCs.PrimordialWyrm; using CalamityMod.NPCs.VanillaNPCAIOverrides; using CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses; +using CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses.BrainOfCthulhu; using CalamityMod.NPCs.VanillaNPCAIOverrides.MiniBosses; using CalamityMod.NPCs.VanillaNPCAIOverrides.RegularEnemies; using CalamityMod.Systems.Collections; @@ -144,7 +145,7 @@ public sealed partial class CalamityVanillaAIOverrideNPC : GlobalNPC case NPCID.BrainofCthulhu: return new BrainOfCthulhuAI(); case NPCID.Creeper: - return new BrainOfCthulhuAI.CreeperAI(); + return new CreeperAI(); case NPCID.QueenBee: return new QueenBeeAI(); @@ -920,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/DevourerofGods/DevourerofGodsHead.cs b/NPCs/DevourerofGods/DevourerofGodsHead.cs index 7ab65c83bb..4a19347ddb 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; @@ -33,6 +32,7 @@ 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; @@ -304,6 +304,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("Mods.CalamityMod.DevourerOfGods.Phases", NPC, 0, 120, false, new BossText()); + } + public override void SendExtraAI(BinaryWriter writer) { bool wasDyingBefore = Dying; @@ -634,7 +643,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("Mods.CalamityMod.DevourerOfGods.Phases", NPC, 2, 120, false, new BossText()); } } @@ -811,7 +820,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("Mods.CalamityMod.DevourerOfGods.Phases", NPC, 3, 120, false, new BossText()); } spawnedGuardians3 = true; @@ -1474,7 +1483,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("Mods.CalamityMod.DevourerOfGods.Phases", NPC, 1, 120, false, new BossText()); } NPC.TargetClosest(); @@ -2502,7 +2511,7 @@ namespace CalamityMod.NPCs.DevourerofGods spriteBatch.Draw(mainJawGlowTexture, jawDrawPosition, null, NPC.GetAlpha(Color.White), NPC.rotation + JawRotation * i, jawOrigin, NPC.scale, jawSpriteEffect, 0f); // Draw the additional special jaw textures above these for the Rift Dash attack. - if (GodSlayerDashJawFadeProgress > 0.02f && !DoGDeathAnimationRenderer.ValidToDraw(NPC)) + if (GodSlayerDashJawFadeProgress > 0.02f && CalamityDrawParameterNPC.DoGDeathAnimationTimer <= 0) { using (spriteBatch.Scope()) { @@ -2813,7 +2822,7 @@ namespace CalamityMod.NPCs.DevourerofGods int DialogueIndex; if (target.statLife - hurtInfo.Damage <= 0) { - DialogueGroup = "DevourerOfGods.Death"; + DialogueGroup = "Mods.CalamityMod.DevourerOfGods.Death"; if (counter == 0) if (NPC.GetLifePercent() <= 0.25f) DialogueIndex = 4;// text = "Mods.CalamityMod.Status.Boss.DoGHeadDeath5"; //All that running just to die to a single touch? @@ -2832,7 +2841,7 @@ namespace CalamityMod.NPCs.DevourerofGods { if (counter == 0 && Phase2Started) { - DialogueGroup = "DevourerOfGods.Running"; + DialogueGroup = "Mods.CalamityMod.DevourerOfGods.Running"; if (NPC.GetLifePercent() <= 0.25f) DialogueIndex = 1;// text = "Mods.CalamityMod.Status.Boss.DoGHeadRunning2"; //WHAT'S THE PROBLEM?! CAN'T RUN ANYMORE?! else @@ -2840,7 +2849,7 @@ namespace CalamityMod.NPCs.DevourerofGods } else { - DialogueGroup = "DevourerOfGods.Head"; + DialogueGroup = "Mods.CalamityMod.DevourerOfGods.Head"; if (counter > 9) DialogueIndex = Main.rand.Next(10, 13);// text = headHitKeys[Main.rand.Next(10, 13)]; //DogHead11-13 else if (counter == 9) @@ -2860,7 +2869,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++; } diff --git a/NPCs/ExoMechs/Ares/AresBody.cs b/NPCs/ExoMechs/Ares/AresBody.cs index 3f534839d7..a254f33078 100644 --- a/NPCs/ExoMechs/Ares/AresBody.cs +++ b/NPCs/ExoMechs/Ares/AresBody.cs @@ -186,6 +186,7 @@ namespace CalamityMod.NPCs.ExoMechs.Ares { NPCID.Sets.TrailingMode[Type] = 3; NPCID.Sets.TrailCacheLength[Type] = NPC.oldPos.Length; + NPCID.Sets.NeedsExpertScaling[Type] = true; NPCID.Sets.BossBestiaryPriority.Add(Type); NPCID.Sets.NPCBestiaryDrawModifiers value = new NPCID.Sets.NPCBestiaryDrawModifiers() { diff --git a/NPCs/ExoMechs/Ares/AresGaussNuke.cs b/NPCs/ExoMechs/Ares/AresGaussNuke.cs index 9b2d5e241c..876ab64252 100644 --- a/NPCs/ExoMechs/Ares/AresGaussNuke.cs +++ b/NPCs/ExoMechs/Ares/AresGaussNuke.cs @@ -79,6 +79,7 @@ namespace CalamityMod.NPCs.ExoMechs.Ares this.HideFromBestiary(); NPCID.Sets.TrailingMode[Type] = 3; NPCID.Sets.TrailCacheLength[Type] = NPC.oldPos.Length; + NPCID.Sets.NeedsExpertScaling[Type] = true; if (!Main.dedServ) { GlowTexture = ModContent.Request(Texture + "Glow", AssetRequestMode.AsyncLoad); diff --git a/NPCs/ExoMechs/Ares/AresLaserCannon.cs b/NPCs/ExoMechs/Ares/AresLaserCannon.cs index 0da93c21a7..dadb2b924d 100644 --- a/NPCs/ExoMechs/Ares/AresLaserCannon.cs +++ b/NPCs/ExoMechs/Ares/AresLaserCannon.cs @@ -81,6 +81,7 @@ namespace CalamityMod.NPCs.ExoMechs.Ares this.HideFromBestiary(); NPCID.Sets.TrailingMode[Type] = 3; NPCID.Sets.TrailCacheLength[Type] = NPC.oldPos.Length; + NPCID.Sets.NeedsExpertScaling[Type] = true; if (!Main.dedServ) { GlowTexture = ModContent.Request(Texture + "Glow", AssetRequestMode.AsyncLoad); diff --git a/NPCs/ExoMechs/Ares/AresPlasmaFlamethrower.cs b/NPCs/ExoMechs/Ares/AresPlasmaFlamethrower.cs index ba9bd2cea5..7a94a62176 100644 --- a/NPCs/ExoMechs/Ares/AresPlasmaFlamethrower.cs +++ b/NPCs/ExoMechs/Ares/AresPlasmaFlamethrower.cs @@ -75,6 +75,7 @@ namespace CalamityMod.NPCs.ExoMechs.Ares this.HideFromBestiary(); NPCID.Sets.TrailingMode[Type] = 3; NPCID.Sets.TrailCacheLength[Type] = NPC.oldPos.Length; + NPCID.Sets.NeedsExpertScaling[Type] = true; if (!Main.dedServ) { GlowTexture = ModContent.Request(Texture + "Glow", AssetRequestMode.AsyncLoad); diff --git a/NPCs/ExoMechs/Ares/AresTeslaCannon.cs b/NPCs/ExoMechs/Ares/AresTeslaCannon.cs index ad113bad6e..222bc247ac 100644 --- a/NPCs/ExoMechs/Ares/AresTeslaCannon.cs +++ b/NPCs/ExoMechs/Ares/AresTeslaCannon.cs @@ -77,6 +77,7 @@ namespace CalamityMod.NPCs.ExoMechs.Ares this.HideFromBestiary(); NPCID.Sets.TrailingMode[Type] = 3; NPCID.Sets.TrailCacheLength[Type] = NPC.oldPos.Length; + NPCID.Sets.NeedsExpertScaling[Type] = true; if (!Main.dedServ) { GlowTexture = ModContent.Request(Texture + "Glow", AssetRequestMode.AsyncLoad); diff --git a/NPCs/HiveMind/HiveMind.cs b/NPCs/HiveMind/HiveMind.cs index cf7acffe35..e05c2ed981 100644 --- a/NPCs/HiveMind/HiveMind.cs +++ b/NPCs/HiveMind/HiveMind.cs @@ -47,7 +47,7 @@ namespace CalamityMod.NPCs.HiveMind { string normalIconPath = "CalamityMod/NPCs/HiveMind/HiveMind_Head_Boss"; string phase2IconPath = "CalamityMod/NPCs/HiveMind/HiveMindP2_Head_Boss"; - + normalIconIndex = CalamityMod.Instance.AddBossHeadTexture(normalIconPath, -1); phase2IconIndex = CalamityMod.Instance.AddBossHeadTexture(phase2IconPath, -1); } @@ -277,10 +277,6 @@ namespace CalamityMod.NPCs.HiveMind frameHeight = frameHeight_P2; } - // Update NPC Size accordingly - NPC.width = frameWidth; - NPC.height = frameHeight - 2; //Phase 1 Sprite have 2 pixel margin - NPC.frameCounter += 1.0; // Update each 6 ticks if (NPC.frameCounter >= 6.0) { @@ -416,6 +412,10 @@ namespace CalamityMod.NPCs.HiveMind public override void AI() { + // Update NPC Size according to Phase Changes + NPC.width = frameWidth; + NPC.height = frameHeight - 2; //Phase 1 Sprite have 2 pixel margin + // Get a target if (NPC.target < 0 || NPC.target == Main.maxPlayers || Main.player[NPC.target].dead || !Main.player[NPC.target].active) NPC.TargetClosest(); @@ -1063,7 +1063,7 @@ namespace CalamityMod.NPCs.HiveMind NPC.damage = NPC.defDamage; phase2timer++; - if (phase2timer == (int)(arcTime / (death ? 15f : 20f))) + if (phase2timer % 30 == (int)(arcTime / (death ? 15f : 20f))) { phase2timer = 0; NPC.ai[0] += 1f; diff --git a/NPCs/PrimordialWyrm/PrimordialWyrmBody.cs b/NPCs/PrimordialWyrm/PrimordialWyrmBody.cs index cc76aefa20..3a77d83eb0 100644 --- a/NPCs/PrimordialWyrm/PrimordialWyrmBody.cs +++ b/NPCs/PrimordialWyrm/PrimordialWyrmBody.cs @@ -21,6 +21,7 @@ namespace CalamityMod.NPCs.PrimordialWyrm public override void SetStaticDefaults() { + NPCID.Sets.NeedsExpertScaling[Type] = true; this.HideFromBestiary(); if (!Main.dedServ) { diff --git a/NPCs/PrimordialWyrm/PrimordialWyrmBodyAlt.cs b/NPCs/PrimordialWyrm/PrimordialWyrmBodyAlt.cs index 5a8d2566a7..755a0974c7 100644 --- a/NPCs/PrimordialWyrm/PrimordialWyrmBodyAlt.cs +++ b/NPCs/PrimordialWyrm/PrimordialWyrmBodyAlt.cs @@ -20,6 +20,7 @@ namespace CalamityMod.NPCs.PrimordialWyrm public override LocalizedText DisplayName => CalamityUtils.GetText("NPCs.PrimordialWyrmHead.DisplayName"); public override void SetStaticDefaults() { + NPCID.Sets.NeedsExpertScaling[Type] = true; this.HideFromBestiary(); if (!Main.dedServ) { diff --git a/NPCs/PrimordialWyrm/PrimordialWyrmTail.cs b/NPCs/PrimordialWyrm/PrimordialWyrmTail.cs index 1796a73b70..f1f0da9544 100644 --- a/NPCs/PrimordialWyrm/PrimordialWyrmTail.cs +++ b/NPCs/PrimordialWyrm/PrimordialWyrmTail.cs @@ -19,6 +19,7 @@ namespace CalamityMod.NPCs.PrimordialWyrm public override LocalizedText DisplayName => CalamityUtils.GetText("NPCs.PrimordialWyrmHead.DisplayName"); public override void SetStaticDefaults() { + NPCID.Sets.NeedsExpertScaling[Type] = true; this.HideFromBestiary(); if (!Main.dedServ) { 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; diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainIllusion.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainIllusion.cs new file mode 100644 index 0000000000..6f210adc67 --- /dev/null +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainIllusion.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.DataStructures; +using Terraria.GameContent; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses.BrainOfCthulhu; + +[AutoloadBossHead] +public class BrainIllusion : ModNPC, ILocalizedModType +{ + public new string LocalizationCategory => "NPCs"; + public override string Texture => "Terraria/Images/NPC_266"; + public override string BossHeadTexture => "Terraria/Images/NPC_Head_Boss_23"; + + ref float Time => ref NPC.ai[0]; + + ref float AttackValue => ref NPC.ai[1]; + + ref float Angle => ref NPC.ai[2]; + + ref float TeleportDuration => ref NPC.localAI[0]; + + ref float TeleportTime => ref NPC.ai[3]; + + private Vector2 OldPos = Vector2.zeroVector; + + public override void SetStaticDefaults() + { + this.HideFromBestiary(); + Main.npcFrameCount[Type] = 8; + } + + public override void SetDefaults() + { + NPC.width = 160; + NPC.height = 110; + NPC.damage = 20; + NPC.lifeMax = 1; + NPC.knockBackResist = 0f; + NPC.noGravity = true; + NPC.noTileCollide = true; + NPC.boss = true; + NPC.dontTakeDamage = true; + NPC.chaseable = false; + NPC.npcSlots = 0f; + NPC.netAlways = true; + Music = MusicID.Boss3; + } + + public override void OnSpawn(IEntitySource source) + { + TeleportDuration = AttackValue; + AttackValue = 0; + TeleportTime = Time; + } + + public override void AI() + { + if (NPC.crimsonBoss == -1) + { + NPC.active = false; + return; + } + NPC brain = Main.npc[NPC.crimsonBoss]; + Player target = Main.player[brain.target]; + NPC.GivenName = brain.GivenOrTypeName + $": {brain.life}/{brain.lifeMax}"; + + #region Attack Start + if (Time < 30) + { + TeleportDuration = 30; + + if (Time == (TeleportDuration / 2f) && AttackValue == 0) + { + AttackValue = 1; + } + else + { + TeleportTime--; + } + + NPC.Opacity = 1 - (TeleportTime / (TeleportDuration / 2f)); + } + #endregion + else + { + if (Time == 30) + { + 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(OldPos, target.Center + (Angle.ToRotationVector2() * circleDist), lerp); + Angle += MathHelper.Lerp(0f, BrainOfCthulhuAI.IllusionDashStartingSpinSpeed, CalamityUtils.SineInEasing(lerp, 1)); + } + else if (Time <= 60f + BrainOfCthulhuAI.IllusionDashSpinDuration) + { + NPC.Center = target.Center + Angle.ToRotationVector2() * BrainOfCthulhuAI.IllusionDashCloseInDistance; + + Angle += MathHelper.Lerp(BrainOfCthulhuAI.IllusionDashStartingSpinSpeed, 0f, CalamityUtils.SineOutEasing((Time - 60) / (float)BrainOfCthulhuAI.IllusionDashSpinDuration, 1)); + } + else if (Time <= 90 + BrainOfCthulhuAI.IllusionDashSpinDuration) + { + float reelBackSpeedExponent = 2.6f; + float reelBackCompletion = Utils.GetLerpValue(0f, 30, Time - (60 + BrainOfCthulhuAI.IllusionDashSpinDuration), true); + float reelBackSpeed = MathHelper.Lerp(4f, 20f, MathF.Pow(reelBackCompletion, reelBackSpeedExponent)); + Vector2 reelBackVelocity = (Angle + MathHelper.Pi).ToRotationVector2() * -reelBackSpeed; + NPC.velocity = Vector2.Lerp(NPC.velocity, reelBackVelocity, 0.25f); + } + else if (Time == 91 + BrainOfCthulhuAI.IllusionDashSpinDuration) + NPC.velocity = (Angle + MathHelper.Pi).ToRotationVector2() * BrainOfCthulhuAI.IllusionDashVelocity; + else if (Time <= 91 + BrainOfCthulhuAI.IllusionDashSpinDuration + BrainOfCthulhuAI.IllusionDashTeleportDuration) + { + NPC.Opacity = MathHelper.Lerp(1f, 0.25f, CalamityUtils.SineInEasing((Time - (91 + BrainOfCthulhuAI.IllusionDashSpinDuration)) / (float)BrainOfCthulhuAI.IllusionDashTeleportDuration, 1)); + if (NPC.Opacity < 0.666f) + NPC.damage = 0; + } + else + NPC.active = false; + } + + 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; + if (NPC.frameCounter > 6.0) + { + NPC.frameCounter = 0.0; + NPC.frame.Y += frameHeight; + } + + if (NPC.frame.Y < frameHeight * 4) + { + NPC.frame.Y = frameHeight * 4; + } + if (NPC.frame.Y > frameHeight * 7) + { + NPC.frame.Y = frameHeight * 4; + } + } + + public override bool? CanBeHitByItem(Player player, Item item) => false; + public override bool? CanBeHitByProjectile(Projectile projectile) => false; + + public override bool PreDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) + { + Vector2 drawPos = NPC.Center + (Vector2.UnitY * 16) - Main.screenPosition; + Vector2 scale = Vector2.One; + + if (TeleportTime != 0) + { + //Color glowColor = Color.White * (teleportCounter / 30f); + scale = Vector2.Lerp(Vector2.One, new Vector2(0.5f + ((float)Math.Cos(Time / (TeleportDuration / 2f) * MathHelper.TwoPi) / 2f + 0.5f), 0.5f + ((float)Math.Sin(Time / (TeleportDuration / 2f) * MathHelper.TwoPi) / 2f + 0.5f)), CalamityUtils.SineInOutEasing(TeleportTime / (TeleportDuration / 2f), 1)); + + spriteBatch.Draw(TextureAssets.Npc[NPCID.BrainofCthulhu].Value, drawPos, NPC.frame, Lighting.GetColor(NPC.Center.ToTileCoordinates()) * NPC.Opacity, NPC.rotation, NPC.frame.Size() * 0.5f, scale * NPC.scale, 0, 0); + //spriteBatch.Draw(GetBrainGlow(), drawPos, npc.frame, glowColor, npc.rotation, npc.frame.Size() * 0.5f, scale, 0, 0); + } + else + spriteBatch.Draw(TextureAssets.Npc[NPCID.BrainofCthulhu].Value, drawPos, NPC.frame, Lighting.GetColor(NPC.Center.ToTileCoordinates()) * NPC.Opacity, NPC.rotation, NPC.frame.Size() * 0.5f, scale * NPC.scale, 0, 0); + return false; + } +} diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs new file mode 100644 index 0000000000..dd315cab0b --- /dev/null +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs @@ -0,0 +1,2852 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.DataStructures; +using CalamityMod.Events; +using CalamityMod.NPCs; +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 Microsoft.Xna.Framework.Graphics.PackedVector; +using ReLogic.Content; +using Terraria; +using Terraria.Audio; +using Terraria.Chat; +using Terraria.DataStructures; +using Terraria.GameContent; +using Terraria.Graphics.Effects; +using Terraria.Graphics.Shaders; +using Terraria.ID; +using Terraria.Localization; +using Terraria.ModLoader; +using Terraria.ModLoader.IO; + +namespace CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses.BrainOfCthulhu; + +public class BrainOfCthulhuAI : VanillaAIOverride +{ + private static SoundStyle StunnedHit = new("CalamityMod/Sounds/Custom/BrainOfCthulhu/BoC_Rev_Stun_Hit", 3); + private static SoundStyle ShieldDown = new("CalamityMod/Sounds/Custom/BrainOfCthulhu/BoC_Rev_Shield_Down"); + private static SoundStyle ShieldUp = new("CalamityMod/Sounds/Custom/BrainOfCthulhu/BoC_Rev_Shield_Up"); + private static SoundStyle IntroRoar = new("CalamityMod/Sounds/Custom/BrainOfCthulhu/BoC_Rev_Roar"); + private static SoundStyle Roar = new("CalamityMod/Sounds/Custom/BrainOfCthulhu/BoC_Rev_Short_Roar"); + + internal static bool SummonedViaItem = false; + internal List BoCAfterImages = []; + internal float ShieldOpacity = 1f; + internal float ShieldScale = 1f; + private Vector2 BoCDrawOffset = Vector2.Zero; + private Rectangle BoCFrame = new(0, 0, 198, 180); + + #region Balancing Values + + internal static int BrainIllusionDamage => 15; + + #region Projectile Damage Values + internal static int BloodShotDamage => 12; // 48 + internal static int BloodScytheDamage => 12; // 48 + internal static int IchorShotDamage => 12; // 48 + internal static int CrimsonEyeDamage => 12; // 48 + #endregion + + internal static float Phase1DefenseMultiplier => 1.5f; //Multiplies BoC's default defense value by this amount when in Phase 1. + + #region Health Gates + internal static float DesperateOnslaughtCreeperHealthGate => 0.1f; //When the cumulative health % of all creepers falls below this value, BoC will begin its pre-stun attack upon entering its idle phase. + internal static float Phase2HealthGate => 0.5f; //When BoC's health % falls below this value, it will begin entering Phase 2 + #endregion + + internal static float DespawnRange => 6000f; + + #region Phase 1 Attack Values + + #region Idle Period + internal static int IdlePeriodDuration => 180; + internal static int CreeperChargeDelayMin => 70; + internal static int CreeperChargeDelayMax => 100; + internal static int CreeperChargePositioningTime => 60; + internal static int CreeperChargeWindUpTime => 22; + #endregion + + internal static int StunDuration => 480; + + #region Creeper Swipes + internal static int SwipesStartupDuration => 120; + internal int SwipeDuration => 60 + SwipeDelay; + internal int SwipeDelay => AttackFlag ? 30 : CalamityWorld.death ? 30 : 45; + internal static int SwipeAmount => 4; + internal int SwipeIchorDelay => 30 + SwipeDelay; + #endregion + + #region Creeper Crush + internal static int LightSwipeDelay => 60; + internal static int LightSwipeAmount => CalamityWorld.death ? 8 : 6; + internal static int LightSwipeTravelTime => 30; + internal static int LightSwipeAttackDelay => 10; + internal static int LightSwipeDuration => CalamityWorld.death ? 45 : 60; + internal static int StrongSwipeDelay => 90; + internal static int StrongSwipeAmount => CalamityWorld.death ? 7 : 5; + internal static int StrongSwipeTravelTime => 45; + internal static int StrongSwipeAttackDelay => 15; + internal static int StrongSwipeDuration => CalamityWorld.death ? 60 : 80; + #endregion + + #region Creeper Orbit + internal static int OrbitSetupDuration => 60; + internal static int OrbitDuration => 720; + internal static int OrbitAttackInterval => 120; + internal static int OrbitAttackParticipantCount => CalamityWorld.death ? 4 : 3; + internal static float OrbitStandardRadius => 320f; + internal static float OrbitTelegraphRadius => 480f; + internal static float BaseRotationSpeed => 0.0175f; + #endregion + + #region Creeper Spiral + internal static int SpiralDuration => 720; + internal static int SpiralSetupTime => 90; + internal static int TendrilCount => 3; + internal static float TendrilLength => 512; + internal static float TendrilStartDistance => 64; + internal static float MaxCreeperSway => 64; + internal static int StartingTimePerRevolutionMax => 270; + internal static int StartingTimePerRevolutionMin => 180; + internal static int EndingTimePerRevolutionMax => 210; + internal static int EndingTimePerRevolutionMin => 120; + internal static int SpeedUpDelayTime => 120; + internal static int SpeedUpExtensionTime => 120; + internal static float TurnAroundRatio => 0.6f; //In the second creeper phase, the creeper spiral will turn around at this completion percentage of the attack; + internal static float TurnAroundDurationRatio => 0.1f; //The amount of time that it'll take for the creeper spiral to turn around + + #endregion + + #endregion + + #region Phase 2 Attack Values + + internal static float DefaultTeleportDistance => 360f; + + #region Idle Period + internal static int ChaseTime => 160; + internal static int MaxChases => 3; + internal static int IdleTeleportDuration => CalamityWorld.death ? 36 : 44; + #endregion + + #region Bloodletting + internal static int BloodlettingDuration => 765; + internal static Vector2 HoverDistance => new (420f, 270f); + internal static float HoverEndHeight => 300f; + internal static int IchorRate => CalamityWorld.death ? 8 : 10; + internal static float IchorSpread => 1.5f; + internal static float IchorVelocity => 3f; + internal static int BloodshotRate => 90; + internal static float BloodshotVelocity => 10f; + internal static int DashPrepTime => 90; + internal static int DashReelbackTime => 20; + internal static int DashDuration => 30; + internal static float DashVelocity => 32f; + internal static int DashScytheRate => CalamityWorld.death ? 5 : 6; + #endregion + + #region Sanguine Scythes + internal static int SanguineTeleportCount => 5; + internal static int SanguineScytheCount => CalamityWorld.death ? 12 : 10; + internal static int SanguineTeleportDuration => 30; + internal static float SanguineTeleportDistance => 440f; + internal static Vector2 SanguineFinalTeleportOffset => new(720, 300); + internal static int SanguineAttackEndDelay => 30; + internal static int SanguineAttackEndDuration => 100; + internal static int SanguineAttackEndIchorRate => 10; + + #endregion + + #region Crimson Eyes + internal static int CrimsonEyeAttackIdleDuration => 210; + internal static int CrimsonEyeAttackSetUpDuration => 30; + internal static int CrimsonEyeAttackBuildUpDuration => 120; + + internal static int CrimsonEyeRate => 60; + internal static int CrimsonEyeCap => 40; + + internal static int CrimsonEyeAttackDuration => 960; + internal static int CrimsonEyeAttackEndDuration => 210; + internal static float TurnAccelerationMultiplier => 0.01f; //Base multiplier for the boss' course correction rotation + internal static float TurnAccelerationDistanceBuffer => 160f; //Determines the minimum distance it must be at before it can begin redirecting. + internal static float TurnAccelerationDistanceDivisor => 72f; //Determines how much the distance affects its turn amount. Larger number means it must get further from the player in order to correct its course + #endregion + + #region Illusion Dash + internal static float IllusionDashTeleportDistance => 300f; + internal static int IllusionDashTeleportDuration => 30; + internal static float IllusionDashCloseInDistance => 300f; + internal static float IllusionDashStartingSpinSpeed => 0.125f; + internal static int IllusionDashSpinDuration => 100; + internal static int IllusionDashFakeoutTeleportDuration => 16; + internal static float IllusionDashVelocity => 30f; + + #endregion + + #region Illusion Trick + internal static int IllusionTrickAngleGroups => CalamityWorld.death ? 8 : 6; + internal static int IllusionTrickGroupSize => CalamityWorld.death ? 5 : 4; + internal static int IllusionTrickStunDuration => 120; + internal static int IllusionTrickTimeLimit => 960; + + #endregion + + #endregion + + #endregion + + internal enum BrainAIState : byte + { + //Spawn Animation + UndergroundSpawnAnimation, + SurfaceSpawnAnimation, + //Phase 1 + Phase1Idle, + CreeperSwipes, + CreeperSwings, + CreeperOrbit, + CreeperSpiral, + TelekineticOnslaught, + Stunned, + //Phase Transition + Phase2TransitionClosed, + Phase2TransitionOpen, + //Phase 2 + Phase2Idle, + CrimsonEyes, + SanguineScythes, + Bloodletting, + IllusionDash, + IllusionTrick, + //Defeat + DeathAnimation + } + + internal BrainAIState AIState { get => (BrainAIState)NPC.ai[0]; set => NPC.ai[0] = (float)value; } + internal BrainAIState PreviousAttack = BrainAIState.Phase1Idle; + internal ref float Time => ref NPC.ai[1]; + internal ref float DespawnTime => ref NPC.ai[2]; + internal ref float AnimationTime => ref NPC.ai[3]; + internal float TeleportTime = 0; + internal float TeleportDuration = 0; + internal float SpawnTime = 0; + internal int SpawnDelay = 0; + internal bool OnSecondCreeperPhase = false; + + internal float CachedRatio = 0f; + private bool isNegative = false; + internal int AttackSign { get => isNegative ? -1 : 1; set => isNegative = value == -1 ? true : false; } + internal float AttackRotation = 0; + internal float AttackTime = 0; + internal int AttackCounter = 0; + internal bool AttackFlag = false; + internal Vector2 AttackPosition = Vector2.Zero; + internal List availableAttacks = []; + internal List AttackList = []; + + private Player Target => Main.player[NPC.target]; + + private static float CreeperHPRatio { get + { + float ratio = 0f; + foreach (NPC creeper in Main.npc.Where(n => n.active && n.type == NPCID.Creeper)) + ratio += creeper.life / (float)creeper.lifeMax; + if (ratio != 0f) + ratio /= GetBrainOfCthuluCreepersCountRevDeath(); + return ratio; + } + } + + private static float CreeperAmountRatio => NPC.CountNPCS(NPCID.Creeper) / (float)GetBrainOfCthuluCreepersCountRevDeath(); + + public override bool EnableMultiplayerSmoothingAheadOfAI => true; + + public override void SetDefaults(Mod mod) + { + NPC.damage = NPC.defDamage = 36; // 64 (1.8x expert scaling) + BoCDrawOffset = Vector2.Zero; + ShieldOpacity = 1f; + ShieldScale = 1f; + BrainOfCthulhuSystem.ScreenBlurStrength = 0f; + + if (!Main.dedServ) + { + int brainOfCthuluCreepersCount = GetBrainOfCthuluCreepersCountRevDeath(); + BrainOfCthulhuSystem.VerletTendrils = new List[brainOfCthuluCreepersCount]; + + for (int i = 0; i < brainOfCthuluCreepersCount; i++) + { + List tendril = []; + for (int j = 0; j < 28; j++) + tendril.Add(new(NPC.Center)); + + BrainOfCthulhuSystem.VerletTendrils[i] = tendril; + } + } + } + + public override void OnSpawn(Mod mod) + { + 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 + CalamityTargetingParameters options = CalamityTargetingParameters.BossDefaults; + options.aggroRatio = -1f; + options.finishThemOff = true; + CalamityUtils.CalamityTargeting(NPC, options); + } + Player target = Main.player[NPC.target]; + 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; + PreviousAttack = BrainAIState.Phase1Idle; + SpawnDelay = SummonedViaItem ? 2 : 60; + if (SummonedViaItem) + SpawnTime = -1; + + if (Main.netMode != NetmodeID.MultiplayerClient) + { + int brainOfCthuluCreepersCount = GetBrainOfCthuluCreepersCountRevDeath(); + for (int i = 0; i < brainOfCthuluCreepersCount; i++) + NPC.NewNPC(NPC.GetSource_FromAI(), (int)NPC.Center.X, (int)NPC.Center.Y, NPCID.Creeper, NPC.whoAmI, i, ai2: -1); + } + } + + public override bool AI(Mod mod) + { + // whoAmI variable + NPC.crimsonBoss = NPC.whoAmI; + bool phase2 = AIState >= BrainAIState.Phase2TransitionClosed; + + //Takes more damage in Phase 1 to account for invulnerability phases + if (phase2) + { + NPC.knockBackResist = 0f; + NPC.defense = NPC.defDefense; + + NPC.chaseable = (AIState != BrainAIState.IllusionDash && AIState != BrainAIState.IllusionTrick); + } + else + NPC.defense = (int)(NPC.defDefense * Phase1DefenseMultiplier); + + if (AIState <= BrainAIState.SurfaceSpawnAnimation) + NPC.damage = 0; + else + NPC.damage = NPC.defDamage; + + #region Targeting + 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 + CalamityTargetingParameters options = CalamityTargetingParameters.BossDefaults; + options.aggroRatio = -1f; + options.finishThemOff = true; + CalamityUtils.CalamityTargeting(NPC, options); + } + #endregion + + #region Despawn + // Despawn check + bool despawn = (Target.dead || !Target.ZoneCrimson) && !BossRushEvent.BossRushActive; + + // Despawn + if (despawn) + { + if (DespawnTime < 90) + DespawnTime += 1f; + + if (DespawnTime == 90) + NPC.velocity.Y += 0.1f; + } + else if (DespawnTime > 0f) + DespawnTime -= 1f; + + if (Main.netMode != NetmodeID.MultiplayerClient) + { + if (Target.Distance(NPC.Center) > DespawnRange) + { + NPC.active = false; + NPC.life = 0; + + if (Main.dedServ) + NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, NPC.whoAmI, 0f, 0f, 0f, 0, 0, 0); + } + } + + if(DespawnTime > 60) + return false; + #endregion + + #region Hit Sounds + if (AIState == BrainAIState.Stunned) + NPC.HitSound = StunnedHit; + else + NPC.HitSound = SoundID.NPCHit9; + #endregion + + #region Forced State Changes + if (!phase2 && CreeperHPRatio == 0f && AIState != BrainAIState.Stunned && AIState >= BrainAIState.Phase1Idle) + { + AIState = BrainAIState.Stunned; + Time = 0; + ResetAttackValues(); + foreach(Projectile p in Main.ActiveProjectiles) + { + if (p.type != ModContent.ProjectileType()) + continue; + + p.ai[1] = 0; + } + } + + if (AIState == BrainAIState.Stunned && (NPC.life / (float)NPC.lifeMax) < Phase2HealthGate) + { + AIState = BrainAIState.Phase2TransitionClosed; + Time = 0; + TeleportTime = 0; + } + #endregion + + switch (AIState) + { + #region Spawn Animations + case BrainAIState.UndergroundSpawnAnimation: + case BrainAIState.SurfaceSpawnAnimation: + SpawnAnimation(); + break; + #endregion + + #region Phase 1 + case BrainAIState.Phase1Idle: + Phase1Idle(); + break; + case BrainAIState.TelekineticOnslaught: + TelekineticOnslaught(); + break; + case BrainAIState.Stunned: + Stunned(); + break; + case BrainAIState.CreeperSwipes: + CreeperSwipes(); + break; + case BrainAIState.CreeperSwings: + CreeperSwings(); + break; + case BrainAIState.CreeperOrbit: + CreeperOrbit(); + break; + case BrainAIState.CreeperSpiral: + CreeperSpiral(); + break; + #endregion + + #region Phase Transition + case BrainAIState.Phase2TransitionClosed: + case BrainAIState.Phase2TransitionOpen: + PhaseTransition(); + break; + #endregion + + #region Phase 2 + case BrainAIState.Phase2Idle: + Phase2Idle(); + break; + case BrainAIState.Bloodletting: + Bloodletting(); + break; + case BrainAIState.SanguineScythes: + SanguineScythes(); + break; + case BrainAIState.CrimsonEyes: + CrimsonEyes(); + break; + case BrainAIState.IllusionDash: + IllusionDash(); + break; + case BrainAIState.IllusionTrick: + IllusionTrick(); + break; + #endregion + + case BrainAIState.DeathAnimation: + DeathAnimation(); + break; + } + + #region Projectile Altering + foreach (Projectile p in Main.ActiveProjectiles) + { + if (p.type != ProjectileID.BloodNautilusShot || p.ai[0] == 0) + continue; + + int startUpTime = 20; + float speedUpTime = 30; + float slowDownMult = 0.96f; + float speedUpMult = 1.025f; + if(AIState == BrainAIState.IllusionDash) + { + startUpTime = 20; + speedUpTime = 30; + slowDownMult = 0.96f; + speedUpMult = 1.025f; + } + + if (p.ai[2] <= startUpTime) + p.velocity *= slowDownMult; + else + { + p.velocity *= speedUpMult; + if (p.ai[2] <= startUpTime + speedUpTime) + { + float newAngle = p.ai[1].AngleLerp(p.ai[0] - MathHelper.TwoPi, (p.ai[2] - startUpTime) / speedUpTime); + + p.velocity = newAngle.ToRotationVector2() * p.velocity.Length(); + } + } + p.ai[2]++; + } + #endregion + + NPC.oldVelocity = NPC.velocity; + Time++; + + return false; + } + + #region Attacks + Animations + + private void SpawnAnimation() + { + if (SpawnTime != 0) //BoC should begin appearing + { + float d = Main.LocalPlayer.DistanceSQ(NPC.Center); + float distanceScaleFactor = 1; + if (d > 592900) //770^2 + distanceScaleFactor = 1 / (1 + (((float)Math.Sqrt(d) - 770) / 32f)); + + float spawnCounter = Time - Math.Abs(SpawnTime); + + if (spawnCounter < 180) + { + float shakeIntensity = CalamityUtils.CircOutEasing(spawnCounter / 180f, 1) * 3f * distanceScaleFactor; + Main.LocalPlayer.SetScreenshake(shakeIntensity); + for (int i = 0; i < shakeIntensity; i++) + { + Point start = Target.Center.ToTileCoordinates() + new Point(Main.rand.Next(-64, 65), 48); + for (int j = 0; j < 96; j++) + { + Point current = start - new Point(0, j); + if (!Main.tile[current].IsTileSolid() && Main.tile[current - new Point(0, 1)].TileType == TileID.Crimstone) + Dust.NewDust(current.ToWorldCoordinates(0, -16), 16, 16, DustID.Crimstone, 0, 3); + } + } + } + if (spawnCounter == 180) + NPC.velocity = Vector2.UnitY * (AIState == BrainAIState.UndergroundSpawnAnimation ? 32 : -50); + else if (spawnCounter > 180) + { + NPC.velocity *= 0.955f; + + if (spawnCounter == 240) + { + SoundEngine.PlaySound(IntroRoar, NPC.Center); + + if (Main.netMode == NetmodeID.SinglePlayer) + Main.NewText(Language.GetTextValue("Announcement.HasAwoken", NPC.TypeName), 175, 75); + else if (Main.dedServ) + ChatHelper.BroadcastChatMessage(NetworkText.FromKey("Announcement.HasAwoken", NPC.TypeName), new Color(175, 75, 255)); + } + + if (spawnCounter > 240 && spawnCounter < 390) + { + BrainOfCthulhuSystem.ScreenBlurStrength = 0.5f;// 0.5f; + if (spawnCounter < 250) + BrainOfCthulhuSystem.ScreenBlurStrength = MathHelper.Lerp(0, 0.5f, (spawnCounter - 240) / 10f); + + NPC.frameCounter += 1f; + + BoCDrawOffset = Main.rand.NextVector2Circular(4, 4); + + for (int i = 0; i < 3; i++) + { + Point start = Target.Center.ToTileCoordinates() + new Point(Main.rand.Next(-64, 65), 48); + for (int j = 0; j < 96; j++) + { + Point current = start - new Point(0, j); + if (!Main.tile[current].IsTileSolid() && Main.tile[current - new Point(0, 1)].TileType == TileID.Crimstone) + Dust.NewDust(current.ToWorldCoordinates(0, -16), 16, 16, DustID.Crimstone, 0, 3); + } + } + + Main.LocalPlayer.SetScreenshake(6 * BrainOfCthulhuSystem.ScreenBlurStrength * distanceScaleFactor); + + if (spawnCounter % 15 == 0) + { + BossRoar pulse = new(NPC.Center, Color.Black, Main.rand.NextFloatDirection(), 0.1f, 3f, 30); + GeneralParticleHandler.SpawnParticle(pulse); + } + } + else if (spawnCounter >= 390 && spawnCounter <= 420) + { + BrainOfCthulhuSystem.ScreenBlurStrength = MathHelper.Lerp(0.5f, 0f, (spawnCounter - 390) / 30f); + BoCDrawOffset *= 0.75f; + } + else if (spawnCounter > 420) + { + BrainOfCthulhuSystem.ScreenBlurStrength = 0f; + BoCDrawOffset = Vector2.Zero; + AIState = BrainAIState.Phase1Idle; + ResetAttackValues(); + Time = -1; + SpawnTime = -1; + Main.musicFade[Main.curMusic] = 1f; + return; + } + } + } + if (AttackCounter < GetBrainOfCthuluCreepersCountRevDeath()) + { + if (SpawnTime == 0) + { + NPC.Center = Target.Center + Vector2.UnitY * (AIState == BrainAIState.UndergroundSpawnAnimation ? -900 : 900); + DisableMultiplayerSmoothing = true; + } + + if (SpawnDelay <= 0) + { + 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); + } + + if (creepers.Count > 0) + { + NPC creeper = creepers[rand]; + creeper.AIOverride().Time = 0; + + AttackCounter++; + + if (SummonedViaItem) + SpawnDelay = 2; + else + switch (AttackCounter) + { + case 1: + SpawnDelay = 90; + break; + case 2: + case 3: + case 4: + SpawnDelay = 24; + break; + case 5: + SpawnDelay = 60; + break; + case 6: + case 7: + case 8: + SpawnDelay = 24; + break; + case 9: + SpawnDelay = 60; + break; + default: + SpawnDelay = 4; + break; + } + } + else + SpawnTime = Time; + } + else + SpawnDelay--; + } + else if (SpawnTime == 0) + SpawnTime = Time; + } + + #region Phase 1 + + private void Phase1Idle() + { + #region Attack Selection + if (CreeperHPRatio <= DesperateOnslaughtCreeperHealthGate) + { + Time = -1; + AIState = BrainAIState.TelekineticOnslaught; + AttackSign = Main.rand.NextBool() ? -1 : 1; + NPC.netUpdate = true; + } + else if (Time > IdlePeriodDuration) + { + Time = -1; + + ResetAttackValues(); + + if (availableAttacks.Count == 0) + { + availableAttacks = [BrainAIState.CreeperSwipes, BrainAIState.CreeperSwings, BrainAIState.CreeperOrbit, BrainAIState.CreeperSpiral]; + if (PreviousAttack != BrainAIState.Phase1Idle) + availableAttacks.Remove(PreviousAttack); + } + + int pick = Main.rand.Next(availableAttacks.Count); + AIState = availableAttacks[pick]; + availableAttacks.RemoveAt(pick); + PreviousAttack = AIState; + + foreach (NPC creep in Main.npc.Where(n => n.active && n.type == NPCID.Creeper)) + creep.AIOverride().Time = -1; + + NPC.netUpdate = true; + } + #endregion + + /* + #region Creeper Attacks + if (AttackCounter > 0) + AttackCounter--; + else if (Time < IdlePeriodDuration - 120) + { + if (Time >= 30) + { + bool targetLeft = target.Center.X < NPC.Center.X; + List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1 && n.AIOverride().CreeperID % 2 == (targetLeft ? 0 : 1)).ToList(); + if (creepers.Count == 0) + creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1).ToList(); + + if (creepers.Count > 0) + { + int rand = Main.rand.Next(creepers.Count); + + NPC creeper = creepers[rand]; + creeper.AIOverride().Time = 0; + } + } + AttackCounter = (int)MathHelper.Lerp(CreeperChargeDelayMax, CreeperChargeDelayMin, 1 - CreeperAmountRatio); + } + #endregion + */ + + #region Movement + if (Time == 0) + { + AttackSign = Main.rand.NextBool() ? -1 : 1; + NPC.netUpdate = true; + foreach (NPC creeper in Main.ActiveNPCs) + { + if (creeper.type != NPCID.Creeper) + continue; + creeper.netUpdate = true; + } + } + + float rotateDir = AttackSign; + Vector2 fromTarget = NPC.DirectionFrom(Target.Center); + Vector2 dir = fromTarget.RotatedBy(Math.Sin(Time / 60f) * rotateDir) * new Vector2(2, 1); + float rayDist = CalamityUtils.PreciseDistanceToTileCollisionHit(Target.Center, dir.ToRotation(), 360, 1); + Vector2 offset = dir * (rayDist - NPC.width); + Vector2 goalPos = Target.Center + offset; + float distSQ = NPC.DistanceSQ(goalPos); + if (distSQ > 129600) + { + NPC.velocity = NPC.DirectionTo(goalPos) * (4 + (NPC.Distance(goalPos) - 360) / 64f); + } + else if (distSQ <= 2048) + { + NPC.velocity *= 0.9f; + } + else if (NPC.velocity.LengthSquared() < 16f) + { + NPC.velocity += NPC.DirectionTo(goalPos).SafeNormalize(Vector2.Zero) * 0.15f; + } + else + { + NPC.velocity = NPC.DirectionTo(goalPos).SafeNormalize(Vector2.Zero) * 6f; + } + #endregion + } + + private void TelekineticOnslaught() + { + #region Movement + if (Collision.SolidCollision(NPC.position, NPC.width, NPC.height)) + { + NPC.velocity = NPC.DirectionTo(Target.Center) * 4f; + Time = -1; + } + else if (NPC.DistanceSQ(Target.Center) > 230400) + NPC.velocity = NPC.DirectionTo(Target.Center) * (NPC.Distance(Target.Center) - 480) / 128f; + else + NPC.velocity *= 0.9f; + #endregion + + float wrappedCounter = Time % 90; + + 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; + + NPC.frameCounter += 1f; + + for (int i = 0; i < 3; i++) + { + Point start = Target.Center.ToTileCoordinates() + new Point(Main.rand.Next(-64, 65), 48); + for (int j = 0; j < 96; j++) + { + Point current = start - new Point(0, j); + if (!Main.tile[current].IsTileSolid() && Main.tile[current - new Point(0, 1)].TileType == TileID.Crimstone) + Dust.NewDust(current.ToWorldCoordinates(0, -16), 16, 16, DustID.Crimstone, 0, 3); + } + } + + float d = Main.LocalPlayer.DistanceSQ(NPC.Center); + float distanceScaleFactor = 1; + if (d > 592900) //770^2 + distanceScaleFactor = 1 / (1 + (((float)Math.Sqrt(d) - 770) / 32f)); + + Main.LocalPlayer.SetScreenshake(4 * BrainOfCthulhuSystem.ScreenBlurStrength * distanceScaleFactor); + + if (Time % 15 == 0) + { + BossRoar pulse = new(NPC.Center, Color.Black, Main.rand.NextFloatDirection(), 0.1f, 3f, 30); + GeneralParticleHandler.SpawnParticle(pulse); + } + } + else + { + BrainOfCthulhuSystem.ScreenBlurStrength = MathHelper.Lerp(0.5f, 0, CalamityUtils.CircOutEasing((Time - 30) / 30f, 1)); + } + } + else + { + BrainOfCthulhuSystem.ScreenBlurStrength = 0f; + if (wrappedCounter == 65) + { + int checkCount = 8; + float wallDist = CalamityUtils.PreciseDistanceToTileCollisionHit(NPC.Center, AttackSign == -1 ? MathHelper.Pi : 0, 480 + NPC.width) - NPC.width; + Vector2[] starts = new Vector2[checkCount]; + for (int i = 0; i < checkCount; i++) + { + float completion = (i + 1) / (float)(checkCount + 1); + starts[i] = NPC.Center + (Vector2.UnitX * ((wallDist * completion) + NPC.width) * AttackSign); + } + + Vector2[] ends = new Vector2[checkCount]; + List goodEnds = []; + List farEnds = []; + List closeEnds = []; + + for (int i = 0; i < checkCount; i++) + { + float maxDist = 960; + float floorDist = CalamityUtils.PreciseDistanceToTileCollisionHit(NPC.Center, Vector2.UnitY.ToRotation(), maxDist); + ends[i] = starts[i] + (Vector2.UnitY * (floorDist + 48)); + if (floorDist >= 600) + farEnds.Add(ends[i]); + else if (floorDist > 240) + goodEnds.Add(ends[i]); + else + closeEnds.Add(ends[i]); + } + + Vector2 chosenEnd; + + if (goodEnds.Count > 0) + chosenEnd = goodEnds[Main.rand.Next(goodEnds.Count)]; + else if (closeEnds.Count > 0) + chosenEnd = closeEnds[Main.rand.Next(closeEnds.Count)]; + else + chosenEnd = farEnds[Main.rand.Next(farEnds.Count)]; + + if (Main.netMode != NetmodeID.MultiplayerClient) + Projectile.NewProjectile(NPC.GetSource_FromThis(), chosenEnd, Vector2.Zero, ModContent.ProjectileType(), 10, 0.5f); + + AttackSign *= -1; + } + } + } + + private void Stunned() + { + #region Movement + NPC.velocity = NPC.velocity.ClampMagnitude(0f, 6f); + if (Time == 0) + { + NPC.velocity = (NPC.Center - Target.Center).SafeNormalize(Vector2.UnitX) * 4f; + SoundEngine.PlaySound(ShieldDown, NPC.Center); + } + + if (NPC.velocity != Vector2.Zero) + { + if (Time >= StunDuration) + NPC.velocity *= 0.8f; + else + NPC.velocity *= 0.93f; + } + + if (Time < StunDuration) + NPC.position.Y += (float)Math.Sin(Time / 8f) * 2 * (1 - MathHelper.Clamp((Time - (StunDuration - 30)) / 30f, 0f, 1f)); + + if (Time <= StunDuration - 30) + { + if (AttackTime > 0) + { + float kbCounter = 30 - AttackTime; + if (kbCounter < 10) + { + float lerp = CalamityUtils.SineOutEasing(kbCounter / 10f, 1); + NPC.rotation = AttackRotation.AngleLerp(-AttackRotation, lerp); + } + else + { + float lerp = CalamityUtils.SineInOutEasing((kbCounter - 10) / 20f, 1); + NPC.rotation = (-AttackRotation).AngleLerp(0, lerp); + } + + } + else if (Math.Abs(NPC.oldVelocity.X) < Math.Abs(NPC.velocity.X) || Time <= 0) + { + AttackRotation = NPC.rotation; + TeleportTime = 0; + } + else + { + TeleportTime++; + NPC.rotation = MathHelper.Lerp(AttackRotation, MathHelper.Pi / 24f * NPC.oldVelocity.X, CalamityUtils.CircOutEasing(MathHelper.Clamp(TeleportTime / 30f, 0f, 1f), 1)); + } + } + #endregion + + #region Tile Collision + if (Time < StunDuration) + { + if (Collision.SolidCollision(NPC.position, NPC.width, NPC.height)) + { + NPC.velocity = NPC.DirectionTo(Target.Center) * 4f; + } + else if (Collision.SolidCollision(NPC.position + NPC.velocity, NPC.width, NPC.height)) + { + if (NPC.velocity.X != NPC.oldVelocity.X) + NPC.velocity.X = -NPC.oldVelocity.X; + if (NPC.velocity.Y != NPC.oldVelocity.Y) + NPC.velocity.Y = -NPC.oldVelocity.Y; + //NPC.velocity *= 2f; + NPC.velocity = NPC.velocity.ClampMagnitude(0f, 8f); + AttackTime = 30; + AttackRotation = NPC.rotation; + } + + if (AttackTime > 0) + { + NPC.knockBackResist = 0f; + AttackTime--; + if (AttackTime == 0) + { + NPC.velocity = Vector2.Zero; + AttackRotation = 0; + } + } + else + NPC.knockBackResist = 1f; + } + #endregion + + BrainOfCthulhuSystem.ScreenBlurStrength = 0f; + + NPC.dontTakeDamage = false; + + if (Time <= 15) + { + float lerp = Time / 15f; + ShieldOpacity = 1 - CalamityUtils.CircOutEasing(lerp, 1); + ShieldScale = MathHelper.Lerp(1f, 1.5f, lerp); + } + + #region Recovery + if (OnSecondCreeperPhase && Time == StunDuration - 30) + { + AIState = BrainAIState.Phase2TransitionClosed; + Time = -1; + TeleportTime = 0; + return; + } + + if (Time > StunDuration - 30) + { + NPC.rotation = NPC.rotation.AngleLerp(0f, CalamityUtils.SineInOutEasing((Time - (StunDuration - 30)) / 30f, 1)); + if (Time == StunDuration - 15) + SoundEngine.PlaySound(ShieldUp, NPC.Center); + } + + if (Time >= StunDuration) + { + if (NPC.velocity.X < 0.001f && NPC.velocity.X < 0.001f) + NPC.velocity = Vector2.Zero; + + int creeperRate = 5; + float wrappedCounter = (Time - StunDuration) % creeperRate; + int spawnTime = GetBrainOfCthuluCreepersCountRevDeath() / 2 * creeperRate; + + if (Time == StunDuration) + AttackCounter = GetBrainOfCthuluCreepersCountRevDeath() - 1; + + NPC.knockBackResist = 0f; + NPC.dontTakeDamage = true; + NPC.rotation = 0f; + + float shieldAppearTime = 15f; + + float lerp = MathHelper.Clamp((Time - StunDuration) / shieldAppearTime, 0f, 1f); + if (lerp >= 1) + { + ShieldOpacity = 1f; + ShieldScale = 1f; + } + else + { + ShieldOpacity = CalamityUtils.CircOutEasing(lerp, 1); + ShieldScale = MathHelper.Lerp(1.5f, 1f, CalamityUtils.SineOutEasing(lerp, 1)); + } + + if (AttackCounter == -1 && Time > StunDuration + spawnTime + 30) + { + OnSecondCreeperPhase = true; + AIState = BrainAIState.Phase1Idle; + Time = -1; + } + else if (AttackCounter > -1 && wrappedCounter == 0) + { + for (int i = 0; i < 2; i++) + { + Vector2 dir = Vector2.UnitY.RotatedBy((AttackCounter % 2 == 0 ? 1 : -1) * (MathHelper.Pi / 16f + ((MathHelper.Pi - MathHelper.Pi / 8f) * (AttackCounter / 2f / (GetBrainOfCthuluCreepersCountRevDeath() / 2f))))); + Vector2 spawnPos = NPC.Center + (dir * 72f); + if (Main.netMode != NetmodeID.MultiplayerClient) + { + NPC creeper = NPC.NewNPCDirect(NPC.GetSource_FromAI(), spawnPos, NPCID.Creeper, NPC.whoAmI, AttackCounter, ai2: -1, ai3: 1); + creeper.velocity = dir * 24f; + } + + for (int j = 0; j < 3; j++) + { + BloodParticle p = new(spawnPos, dir.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 6f, MathHelper.Pi / 6f)) * Main.rand.NextFloat(8f, 12f), 32, 1f, Color.Red); + GeneralParticleHandler.SpawnParticle(p); + } + BloodParticle2 p2 = new(spawnPos, dir * 10f, 16, 0.5f, Color.Red); + GeneralParticleHandler.SpawnParticle(p2); + + if (!Main.dedServ) + { + BrainOfCthulhuSystem.VerletTendrils[(int)AttackCounter] = []; + for (int j = 0; j < 28; j++) + BrainOfCthulhuSystem.VerletTendrils[(int)AttackCounter].Add(new(NPC.Center)); + } + + AttackCounter--; + if (AttackCounter <= -1) + return; + } + + SoundEngine.PlaySound(SoundID.NPCHit9, NPC.Center); + } + } + #endregion + } + + private void CreeperSwipes() + { + //Hand Size check to determine if 1 hand variant should be used + if (Time == 0) + { + int leftAmt = 0; + int rightAmt = 0; + foreach (NPC creeper in Main.ActiveNPCs) + { + if (creeper.type != NPCID.Creeper) + continue; + + if (creeper.AIOverride().CreeperID % 2 == 0) + leftAmt++; + else + rightAmt++; + } + + if (leftAmt > 5 && rightAmt > 5) + { + AttackSign = Main.rand.NextBool() ? -1 : 1; + AttackFlag = false; + } + else + AttackFlag = true; + + NPC.netUpdate = true; + AttackList.Clear(); + } + + float wrappedCount = Time % (SwipeDuration + SwipeDelay); + + if (Time >= SwipesStartupDuration) + { + NPC.damage = NPC.defDamage; + if (wrappedCount == 0) + { + bool useEven = Main.rand.NextBool(); + + bool anyActivated = false; + + foreach (NPC Npc in Main.ActiveNPCs) + { + if (Npc.type != NPCID.Creeper) + continue; + + if (AttackFlag || Npc.AIOverride().CreeperID % 2 == 0! ^ useEven) + { + AttackList.Add((byte)Npc.whoAmI); + //Npc.AIOverride().Time = 0; + anyActivated = true; + } + } + + if (!anyActivated) + foreach (NPC Npc in Main.ActiveNPCs) + { + if (Npc.type != NPCID.Creeper) + continue; + + AttackList.Add((byte)Npc.whoAmI); + //Npc.AIOverride().Time = 0; + } + + NPC.netUpdate = true; + } + else if (wrappedCount == SwipeDuration) + { + AttackSign *= -1; + AttackList.Clear(); + NPC.netUpdate = true; + } + + if (wrappedCount > 1 && wrappedCount <= SwipeIchorDelay && Time % 3 == 0) // Telegraphs ichor rain w/ dripping particles + { + Vector2 spawnPosition = NPC.Center; + spawnPosition.Y += Main.rand.NextFloat(38, 50); + spawnPosition.X += Main.rand.NextFloat(-56, 56); + + BloodParticle blood = new BloodParticle(spawnPosition, Main.rand.NextVector2Unit() * Main.rand.NextFloat(1.5f, 2.5f), Main.rand.Next(30, 40), Main.rand.NextFloat(0.6f, 1f), Color.Gold); + GeneralParticleHandler.SpawnParticle(blood); + } + + if (wrappedCount < 60f) // Vibrates during telegraph + { + Vector2 vibrationVector = Main.rand.NextVector2CircularEdge(1, 1) * MathHelper.Lerp(0f, 12f, CalamityUtils.CircInEasing(wrappedCount / 80f, 1)); + + BoCDrawOffset = vibrationVector; + } + else if (wrappedCount > 60f && wrappedCount < 80f) // Droops down when starting to fire ichor shots + { + float progress = (wrappedCount - 60f) / 20f; + BoCDrawOffset = new Vector2(0, MathHelper.Lerp(10, 0, 1f - (float)Math.Pow(1f - progress, 3f))); + } + + if (Main.netMode != NetmodeID.MultiplayerClient) + if (wrappedCount > SwipeIchorDelay && wrappedCount <= SwipeDuration && Time % 2 == 0) + Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center + new Vector2(Main.rand.NextFloat(-72, 72), 56), Vector2.UnitY.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 4f, MathHelper.Pi / 4f)) * 4f, ProjectileID.GoldenShowerHostile, IchorShotDamage, 0.5f); + + if (Time >= SwipesStartupDuration + ((SwipeDuration + SwipeDelay) * SwipeAmount)) + { + Time = 0; + AIState = BrainAIState.Phase1Idle; + NPC.netUpdate = true; + AttackList.Clear(); + } + } + else + NPC.damage = 0; + + #region Movement + + Vector2 goalPos = Target.Center + (Vector2.UnitY * -270); + float distSQ = NPC.DistanceSQ(goalPos); + if ((Time > SwipesStartupDuration && wrappedCount > 30 && wrappedCount <= SwipeDuration) || NPC.DistanceSQ(goalPos) <= 2048) + NPC.velocity *= 0.9f; + else if (distSQ > 14400) + NPC.velocity = NPC.DirectionTo(goalPos) * (8 + (NPC.Distance(goalPos) - 120) / 16f); + else + NPC.velocity = NPC.DirectionTo(goalPos).SafeNormalize(Vector2.UnitX * -Target.direction) * (8f * distSQ / 14400f); + #endregion + } + + private void CreeperSwings() + { + #region Movement + Vector2 goalDir = Vector2.Zero; + Vector2 fromTarget = NPC.Center - Target.Center; + if (Math.Abs(fromTarget.X) > Math.Abs(fromTarget.Y)) + goalDir = Vector2.UnitX * Math.Sign(fromTarget.X); + else + goalDir = Vector2.UnitY * Math.Sign(fromTarget.Y); + + Vector2 goalPos = Target.Center + (goalDir * 360) - (Vector2.UnitY * 32); + if (NPC.DistanceSQ(goalPos) <= 2048) + NPC.velocity *= 0.9f; + else if (NPC.velocity.LengthSquared() <= 56.25f) //7.5^2 + NPC.velocity += NPC.DirectionTo(goalPos).SafeNormalize(Vector2.UnitX * -Target.direction) * 0.5f; + else + NPC.velocity = NPC.DirectionTo(goalPos).SafeNormalize(Vector2.UnitX * -Target.direction) * 8f; + #endregion + + float delay = OnSecondCreeperPhase ? StrongSwipeDelay : LightSwipeDelay; + if (Time == 0) + AttackList.Clear(); + + if (Time > delay) + { + 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; + int attackDelay; + if (!OnSecondCreeperPhase) + { + crushCount = LightSwipeAmount; + attackDelay = LightSwipeDuration; + } + else + { + crushCount = StrongSwipeAmount; + attackDelay = StrongSwipeDuration; + } + int attackDur = attackDelay * crushCount; + + 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((byte)n.whoAmI)).ToList(); + if (creepers.Count > 1) + { + float rotation; + if (!OnSecondCreeperPhase) + { + rotation = Target.velocity.ToRotation(); + if (Target.velocity == Vector2.Zero) + rotation = Target.direction == 1 ? 0 : MathHelper.Pi; + rotation += Main.rand.NextFloat(-MathHelper.PiOver4 / 2f, MathHelper.PiOver4 / 2f); + } + else + rotation = Main.rand.NextFloat(0, MathHelper.TwoPi); + + int rand = Main.rand.Next(creepers.Count); + NPC first = creepers[rand]; + first.netUpdate = true; + CreeperAI creeper1 = first.AIOverride(); + 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((byte)second.whoAmI); + //creeper2.Time = 0; + creeper2.AttackAngle = rotation + MathHelper.Pi; + + creeper1.PartnerIndex = second.whoAmI; + creeper2.PartnerIndex = first.whoAmI; + } + + NPC.netUpdate = true; + } + + if (Time > delay + attackDur + attackDelay) + { + Time = 0; + AIState = BrainAIState.Phase1Idle; + AttackList.Clear(); + } + } + } + + private void CreeperOrbit() + { + #region Movement + Vector2 fromTarget = (NPC.Center - Target.Center).SafeNormalize(Vector2.UnitX); + Vector2 goalPos = Target.Center + (fromTarget * 440) - (Vector2.UnitY * 32); + float distSQ = NPC.DistanceSQ(goalPos); + if (distSQ > 14400) + NPC.velocity = NPC.DirectionTo(goalPos) * (4 + (NPC.Distance(goalPos) - 120) / 16f); + else + NPC.velocity = NPC.DirectionTo(goalPos).SafeNormalize(Vector2.Zero) * (2 + (2f * (distSQ / 14400))); + #endregion + + if (Time == 0) + { + AttackSign = Main.rand.NextBool() ? -1 : 1; + AttackPosition = Target.Center; + NPC.netUpdate = true; + } + + 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; + AIState = BrainAIState.Phase1Idle; + AttackList.Clear(); + foreach (NPC creep in Main.ActiveNPCs) + { + if (creep.type == NPCID.Creeper) + creep.AIOverride().Time = -1; + } + } + else if (Time >= OrbitAttackInterval && Time < OrbitDuration && Time % OrbitAttackInterval == 0) + { + List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper).ToList(); + if (creepers.Count > 0) + { + int rand = Main.rand.Next(creepers.Count); + for (int i = 0; i < OrbitAttackParticipantCount; i++) + { + if (rand >= creepers.Count) + rand -= creepers.Count; + NPC creeper = creepers[rand]; + AttackList.Add((byte)creeper.whoAmI); + //creeper.AIOverride().Time = 0; + rand += (int)Math.Round(creepers.Count / (float)OrbitAttackParticipantCount); + } + + NPC.netUpdate = true; + } + } + } + + private void CreeperSpiral() + { + if (Time == 0) + { + AttackSign = Main.rand.NextBool() ? -1 : 1; + AttackRotation = 0; + NPC.netUpdate = true; + } + float startTimePerRev = MathHelper.Lerp(StartingTimePerRevolutionMax, StartingTimePerRevolutionMin, 1 - CreeperAmountRatio); + float endTimePerRev = MathHelper.Lerp(EndingTimePerRevolutionMax, EndingTimePerRevolutionMin, 1 - CreeperAmountRatio); + float timePerRev = MathHelper.Lerp(startTimePerRev, endTimePerRev, MathHelper.Clamp((Time - SpeedUpDelayTime) / (SpiralDuration - SpeedUpDelayTime - SpeedUpExtensionTime), 0f, 1f)); + if (Time > SpiralDuration - 30) + timePerRev *= MathHelper.Lerp(1f, 10f, CalamityUtils.CircOutEasing((Time - (SpiralDuration - 30)) / 30f, 1)); + else if (Time < SpiralSetupTime) + timePerRev *= MathHelper.Lerp(1f, 10f, CalamityUtils.CircInEasing(Time / SpiralSetupTime, 1)); + + float rotToAdd = MathHelper.TwoPi / timePerRev * AttackSign; + if (OnSecondCreeperPhase) + { + float attackComplationRatio = Time / SpiralDuration; + float lerp = Utils.GetLerpValue(TurnAroundRatio - (TurnAroundDurationRatio / 2f), TurnAroundRatio + (TurnAroundDurationRatio / 2f), attackComplationRatio, true); + rotToAdd *= MathHelper.Lerp(1, -1, lerp); + } + AttackRotation += rotToAdd; + + if (NPC.DistanceSQ(Target.Center) > 57600) + NPC.velocity = NPC.DirectionTo(Target.Center) * (NPC.Distance(Target.Center) - 240) / 32f; + else + NPC.velocity *= 0.9f; + + if (Time > SpiralDuration) + { + Time = -1; + AIState = BrainAIState.Phase1Idle; + foreach (NPC creep in Main.ActiveNPCs) + { + if (creep.type == NPCID.Creeper) + creep.AIOverride().Time = -1; + } + } + } + + #endregion + + private void PhaseTransition() + { + NPC.dontTakeDamage = true; + NPC.rotation *= 0.9f; + TeleportTime = 0; + + float animCounter = Time - 60; + if (animCounter >= 0) + { + if (animCounter == 0) + NPC.velocity = Vector2.UnitY * 2f; + else if (animCounter < 60) + NPC.velocity *= 0.99f; + else if (animCounter == 60) + NPC.velocity = Vector2.UnitY * -8f; + else if (animCounter == 65) + { + AIState = BrainAIState.Phase2TransitionOpen; + PreviousAttack = BrainAIState.Phase1Idle; + availableAttacks.Clear(); + + SoundEngine.PlaySound(SoundID.NPCHit1, NPC.Center); + + if (!Main.dedServ) + { + //Spawns all of BoC's Phase Transition Gores (GoreIDs 392 -> 395) + for (int i = 392; i <= 395; i++) + Gore.NewGore(NPC.GetSource_FromAI(), NPC.position, Main.rand.NextVector2Circular(6f, 6f), i); + } + + for (int j = 0; j < 20; j++) + Dust.NewDustPerfect(Main.rand.NextVector2FromRectangle(NPC.Hitbox), DustID.Blood, Main.rand.NextVector2Circular(6f, 6f)); + + for (int i = 1; i <= 3; i++) + { + Color color = i switch + { + 1 => Color.Yellow, + 2 => Color.Orange, + _ => Color.Red, + }; + PulseRing ring = new(NPC.Center, NPC.velocity * 0.5f, color, 0f, 1f + i * 0.5f, 24); + GeneralParticleHandler.SpawnParticle(ring); + } + + BoCAfterImages = []; + + SoundEngine.PlaySound(Roar, NPC.Center); + } + else + NPC.velocity *= 0.9f; + + if (animCounter < 60f) + BoCDrawOffset = Main.rand.NextVector2CircularEdge(1, 1) * MathHelper.Lerp(0f, 16f, CalamityUtils.CircInEasing(animCounter / 60f, 1)); + else if (animCounter < 70f) + BoCDrawOffset = Main.rand.NextVector2CircularEdge(1, 1) * MathHelper.Lerp(16f, 0f, CalamityUtils.CircOutEasing((animCounter - 60) / 10f, 1)); + + if (animCounter >= 120f) + { + Time = 0; + ResetAttackValues(); + AIState = BrainAIState.Phase2Idle; + NPC.dontTakeDamage = false; + } + } + else + { + NPC.velocity *= 0.8f; + + #region Tile Collision + if (Collision.SolidCollision(NPC.position, NPC.width, NPC.height)) + { + NPC.velocity = NPC.DirectionTo(Target.Center) * 4f; + } + else if (Collision.SolidCollision(NPC.position + NPC.velocity, NPC.width, NPC.height)) + { + if (NPC.velocity.X != NPC.oldVelocity.X) + NPC.velocity.X = -NPC.oldVelocity.X; + if (NPC.velocity.Y != NPC.oldVelocity.Y) + NPC.velocity.Y = -NPC.oldVelocity.Y; + NPC.velocity *= 2f; + NPC.velocity = NPC.velocity.ClampMagnitude(0f, 8f); + } + #endregion + } + } + + #region Phase 2 + + private void Phase2Idle() + { + //goes from 3 at full health to 1 at low health + int chases = (int)Math.Ceiling(MaxChases * (NPC.life / (float)NPC.lifeMax)); + + NPC.rotation = NPC.velocity.X / 6f * MathHelper.Pi / 8f; + + if (Time == ChaseTime - 5) + AttackCounter++; + + if (Time <= ChaseTime) + { + float speedUp = MathHelper.Clamp((Time - 10) / 10f, 0f, 1f); + float slowDown = 1 - MathHelper.Clamp((Time - (ChaseTime - 15)) / 15f, 0f, 1f); + float angleChange = MathHelper.Lerp(MathHelper.Pi / 24f, 0f, MathHelper.Clamp(Time / (ChaseTime * 0.666f), 0f, 1f)); + NPC.velocity = NPC.velocity.RotateDirectionTowards(NPC.DirectionTo(Target.Center).ToRotation(), angleChange) * (MathHelper.Lerp(3f, 18f, Time / ChaseTime) * speedUp * slowDown); + + if (Time == ChaseTime) + { + Vector2 direction = Target.velocity.SafeNormalize(Vector2.UnitX * Target.direction).RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 3f, MathHelper.Pi / 3f)); + AttackPosition = Target.Center + (direction * DefaultTeleportDistance); + BoCAfterImages = []; + NPC.netUpdate = true; + } + else + { + TeleportTime = 0; + NPC.Opacity = 1f; + } + } + else + { + TeleportDuration = IdleTeleportDuration; + + Vector2 endPoint = AttackPosition; + + NPC.velocity = Vector2.Zero; + + if (Time < ChaseTime + (TeleportDuration / 2f)) + { + if (Time % 4 == 0) + { + Vector2 startPoint = NPC.Center; + + Vector2 direction = endPoint - startPoint; + float curveIntensity = Main.rand.NextFloat(-0.2f, 0.2f); + Vector2 perpindicular = direction.RotatedBy(MathHelper.PiOver2); + + Vector2 controlPoint1 = startPoint + (direction * 0.25f) + (perpindicular * curveIntensity); + Vector2 controlPoint2 = startPoint + (direction * 0.75f) + (perpindicular * curveIntensity); + + BezierCurve path = new BezierCurve(startPoint, controlPoint1, controlPoint2, endPoint); + + BrainOfCthulhuAfterImage afterimage = new(path, NPC.rotation, Vector2.One, (int)(ChaseTime + (TeleportDuration * 0.75f) - Time), BoCFrame); + BoCAfterImages.Add(afterimage); + GeneralParticleHandler.SpawnParticle(afterimage); + } + TeleportTime++; + } + else if (Time == ChaseTime + (TeleportDuration / 2f) && !AttackFlag) + { + Vector2 start = NPC.Center; + NPC.Center = endPoint; + DisableMultiplayerSmoothing = true; + AttackFlag = true; + NPC.netUpdate = true; + } + else + { + TeleportTime--; + if (TeleportTime < 0) + { + TeleportTime = 0; + Time = -1; + AttackFlag = false; + + #region Attack Selection + if (AttackCounter >= chases) //Pick attack + { + NPC.rotation = 0; + ResetAttackValues(); + + if (availableAttacks.Count == 0) + { + bool quickChoice = Main.rand.NextBool(); + availableAttacks = [ + BrainAIState.Bloodletting, + quickChoice ? BrainAIState.SanguineScythes : BrainAIState.IllusionDash, + Main.rand.NextBool() ? BrainAIState.Phase2Idle : BrainAIState.Bloodletting, + quickChoice ? BrainAIState.IllusionDash : BrainAIState.SanguineScythes, + BrainAIState.IllusionTrick + ]; + } + + AIState = availableAttacks[0]; + availableAttacks.RemoveAt(0); + PreviousAttack = AIState; + + if (AIState == BrainAIState.SanguineScythes) + { + Time = -31; + BoCAfterImages = []; + } + + NPC.netUpdate = true; + } + #endregion + } + } + + NPC.Opacity = 1 - (TeleportTime / (TeleportDuration / 2f)); + } + } + + private void Bloodletting() + { + float endTime = Time - BloodlettingDuration; + + #region Main Attack + if (endTime < 0) + { + NPC.rotation = (float)Math.Sin(Time / 8f) * MathHelper.Pi / 8f; + BoCDrawOffset = Vector2.Zero; + + if (Time > BloodshotRate) //Doesnt fire first bloodshot + { + if (Time % IchorRate == 0) + { + if (Time % (IchorRate * 2) == 0) + SoundEngine.PlaySound(SoundID.Item17, NPC.Center); + if (Main.netMode != NetmodeID.MultiplayerClient) + Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center + NPC.velocity + Main.rand.NextVector2Circular(72, 72), new Vector2(Main.rand.NextFloat(-IchorSpread, IchorSpread), -IchorVelocity), ModContent.ProjectileType(), IchorShotDamage, 0.5f); + } + + if (Main.netMode != NetmodeID.MultiplayerClient) + if (Time % BloodshotRate == 0) + { + Vector2 dir = NPC.DirectionTo(Target.Center); + + for (int i = -2; i <= 2; i++) + { + Vector2 initialDir = dir.RotatedBy(i * MathHelper.Pi / 4f); + Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, initialDir * BloodshotVelocity, ProjectileID.BloodNautilusShot, BloodShotDamage, 0.5f, ai0: dir.ToRotation() + MathHelper.TwoPi, ai1: initialDir.ToRotation()); + } + + if (CalamityWorld.death) + { + Vector2 initialDir = dir.RotatedBy(MathHelper.Pi / 6f); + Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, initialDir * BloodshotVelocity / 2f, ProjectileID.BloodNautilusShot, BloodShotDamage, 0.5f, ai0: dir.ToRotation() + MathHelper.TwoPi, ai1: initialDir.ToRotation()); + initialDir = dir.RotatedBy(-MathHelper.Pi / 6f); + Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, initialDir * BloodshotVelocity / 2f, ProjectileID.BloodNautilusShot, BloodShotDamage, 0.5f, ai0: dir.ToRotation() + MathHelper.TwoPi, ai1: initialDir.ToRotation()); + } + } + + + } + } + #endregion + + #region Attack End + else + { + NPC.rotation *= 0.9f; + + if (endTime == 0) + SoundEngine.PlaySound(Roar, NPC.Center); + if (endTime >= DashPrepTime) + { + if (endTime < DashPrepTime + DashReelbackTime) + { + float reelBackSpeedExponent = 2.6f; + float reelBackCompletion = Utils.GetLerpValue(0f, 30, endTime - DashPrepTime, true); + float reelBackSpeed = MathHelper.Lerp(4f, 16f, MathF.Pow(reelBackCompletion, reelBackSpeedExponent)); + Vector2 reelBackVelocity = Vector2.UnitY * -reelBackSpeed; + NPC.velocity = Vector2.Lerp(NPC.velocity, reelBackVelocity, 0.25f); + } + else if (endTime == DashPrepTime + 20) + NPC.velocity = Vector2.UnitY * DashVelocity; + + if (endTime >= DashPrepTime + DashReelbackTime && Time % DashScytheRate == 0) + { + if (Main.netMode != NetmodeID.MultiplayerClient) + { + Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, Vector2.UnitX * 16f, ModContent.ProjectileType(), BloodScytheDamage, 0.5f); + Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, Vector2.UnitX * -16f, ModContent.ProjectileType(), BloodScytheDamage, 0.5f); + } + } + + if (endTime > DashPrepTime + DashReelbackTime + DashDuration) + { + NPC.rotation = 0; + SetupForNextAttack(); + return; + } + } + } + #endregion + + #region Movement + + if (endTime < 0) + { + if (Time == 0) + { + AttackPosition = NPC.Center; + if (NPC.Center.X < Target.Center.X) + AttackSign = -1; + else + AttackSign = 1; + } + + 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 + NPC.Center = goalPos; + } + else if (endTime < DashPrepTime) + { + if (endTime == 0) + NPC.velocity = Vector2.UnitX * AttackSign * 8f; + else + { + Vector2 goalPos = Target.Center - Vector2.UnitY * HoverEndHeight; + Vector2 accel = new Vector2(0.5f, 1.5f); + + NPC.velocity += NPC.DirectionTo(goalPos).SafeNormalize(Vector2.Zero) * accel; + NPC.velocity = NPC.velocity.ClampMagnitude(0f, 8f); + } + } + #endregion + } + + private void SanguineScythes() + { + #region Attack Ending + if (AttackCounter > SanguineTeleportCount) + { + if (Time == SanguineAttackEndDelay) + { + SoundEngine.PlaySound(Roar, NPC.Center); + bool left = Target.Center.X > NPC.Center.X; + NPC.velocity = Vector2.UnitX * (left ? 18 : -18); + NPC.rotation = MathHelper.Pi / 8f * (left ? 1 : -1); + } + if (Time > SanguineAttackEndDelay + SanguineAttackEndDuration) + { + NPC.velocity *= 0.8f; + NPC.rotation *= 0.8f; + } + else if (Time >= SanguineAttackEndDelay && Time % SanguineAttackEndIchorRate == 0) + { + if (Main.netMode != NetmodeID.MultiplayerClient) + { + Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, new Vector2(Math.Sign(NPC.velocity.X), -2f), ModContent.ProjectileType(), IchorShotDamage, 0.5f); + Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, new Vector2(Math.Sign(NPC.velocity.X), -6f), ModContent.ProjectileType(), IchorShotDamage, 0.5f); + } + } + + if (Time > SanguineAttackEndDelay + SanguineAttackEndDuration + 10) + SetupForNextAttack(); + } + #endregion + #region Attack Start + else if (Time < 0) + { + if (Time == -25) + NPC.netUpdate = true; + + if (Time == -24) + { + SoundEngine.PlaySound(Roar, NPC.Center); + + for (int i = 1; i <= 3; i++) + { + Color color = i switch + { + 1 => Color.Yellow, + 2 => Color.Orange, + _ => Color.Red, + }; + PulseRing ring = new(NPC.Center, NPC.velocity * 0.5f, color, 0f, 1f + i * 0.5f, 24); + GeneralParticleHandler.SpawnParticle(ring); + } + } + if (Time == -1) + { + Vector2 direction = Target.velocity.SafeNormalize(Vector2.UnitX * Target.direction).RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 3f, MathHelper.Pi / 3f)); + float distance = SanguineTeleportDistance; + AttackPosition = Target.Center + (direction * distance); + NPC.netUpdate = true; + } + } + #endregion + #region Teleport + else + { + TeleportDuration = SanguineTeleportDuration; + + Vector2 endPoint = AttackPosition; + + if (Time < (TeleportDuration / 2f)) + { + if (Time % 4 == 0) + { + Vector2 startPoint = NPC.Center; + + Vector2 direction = endPoint - startPoint; + float curveIntensity = Main.rand.NextFloat(-0.2f, 0.2f); + Vector2 perpindicular = direction.RotatedBy(MathHelper.PiOver2); + + Vector2 controlPoint1 = startPoint + (direction * 0.25f) + (perpindicular * curveIntensity); + Vector2 controlPoint2 = startPoint + (direction * 0.75f) + (perpindicular * curveIntensity); + + BezierCurve path = new BezierCurve(startPoint, controlPoint1, controlPoint2, endPoint); + + BrainOfCthulhuAfterImage afterimage = new(path, NPC.rotation, Vector2.One, (int)((TeleportDuration * 0.75f) - Time), BoCFrame); + BoCAfterImages.Add(afterimage); + GeneralParticleHandler.SpawnParticle(afterimage); + } + TeleportTime++; + } + else if (Time == (TeleportDuration / 2f) && !AttackFlag) + { + Vector2 start = NPC.Center; + NPC.Center = endPoint; + DisableMultiplayerSmoothing = true; + AttackFlag = true; + NPC.netUpdate = true; + } + else + { + TeleportTime--; + if (TeleportTime < 0) + { + TeleportTime = 0; + Time = -1; + AttackFlag = false; + AttackCounter++; + + if (AttackCounter <= SanguineTeleportCount) + { + SoundStyle explosion = new("CalamityMod/Sounds/Custom/Ravager/RavagerMissileExplosion") + { + Volume = 0.5f + }; + SoundEngine.PlaySound(explosion, NPC.Center); + + for (int i = 0; i < SanguineScytheCount; i++) + { + float initalSpeed = 16f; + if (CalamityWorld.death && i % 2 == 0) + initalSpeed /= 2f; + + if (Main.netMode != NetmodeID.MultiplayerClient) + Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, Vector2.UnitX.RotatedBy(MathHelper.TwoPi / SanguineScytheCount * i) * initalSpeed, ModContent.ProjectileType(), BloodScytheDamage, 0.5f); + } + } + + Vector2 direction; + if (AttackCounter < SanguineTeleportCount) + { + direction = Main.rand.NextFloat(0f, MathHelper.TwoPi).ToRotationVector2(); + AttackPosition = Target.Center + (direction * SanguineTeleportDistance); + } + else + { + direction = Vector2.UnitX * (Main.rand.NextBool() ? -1 : 1); + AttackPosition = Target.Center + (direction * SanguineFinalTeleportOffset.X) + (Vector2.UnitY * -SanguineFinalTeleportOffset.Y); + } + + NPC.netUpdate = true; + + BoCAfterImages = []; + NPC.Opacity = 1f; + } + } + + NPC.Opacity = 1 - (TeleportTime / (TeleportDuration / 2f)); + } + #endregion + } + + //Unused + private void CrimsonEyes() + { + #region Attack Start + if (Time <= 30) + { + if (Time >= 6 && Time <= 12) + { + if (Time == 6) + { + SoundEngine.PlaySound(Roar, NPC.Center); + + for (int i = 1; i <= 3; i++) + { + Color color = i switch + { + 1 => Color.Yellow, + 2 => Color.Orange, + _ => Color.Red, + }; + PulseRing ring = new(NPC.Center, NPC.velocity * 0.5f, color, 0f, 1f + i * 0.5f, 24); + GeneralParticleHandler.SpawnParticle(ring); + } + + CalamityUtils.AddScreenshakeAt(NPC.Center, 10f); + } + + for (int i = 0; i < 12; i++) + { + Point start = Target.Center.ToTileCoordinates() + new Point(Main.rand.Next(-64, 65), 48); + for (int j = 0; j < 96; j++) + { + Point current = start - new Point(0, j); + if (!Main.tile[current].IsTileSolid() && Main.tile[current - new Point(0, 1)].IsTileSolid()) + Dust.NewDust(current.ToWorldCoordinates(0, 0), 16, 16, DustID.Crimstone, 0, 3); + } + } + } + } + #endregion + #region Attack + else + { + #region Eye Spawning + if (Time < CrimsonEyeAttackDuration && CalamityUtils.CountProjectiles(ModContent.ProjectileType()) < CrimsonEyeCap && Time % CrimsonEyeRate == 0) + { + Vector2 spawnPos = Target.Center; + int i = 0; + for (i = 0; i <= 32; i++) + { + spawnPos = Target.Center + Main.rand.NextVector2Circular(256, 256); + + if (Collision.IsWorldPointSolid(spawnPos)) + continue; + + bool alreadyFilled = false; + foreach (Projectile p in Main.ActiveProjectiles) + { + if (p.type != ModContent.ProjectileType()) + continue; + + Rectangle hitbox = new((int)spawnPos.X - 50, (int)spawnPos.Y - 18, 100, 36); + + if (p.Hitbox.Intersects(hitbox)) + { + alreadyFilled = true; + break; + } + } + + if (alreadyFilled) + continue; + + if (Collision.CanHitLine(spawnPos, 1, 1, Target.position, Target.width, Target.height)) + break; + } + + if (i == 32) + spawnPos = Target.Center; + + if (Main.netMode != NetmodeID.MultiplayerClient) + Projectile.NewProjectile(NPC.GetSource_FromThis(), spawnPos, Vector2.Zero, ModContent.ProjectileType(), CrimsonEyeDamage, 0f); + } + #endregion + + #region Early Movement + if (Time < 180) + { + float dist = 210; + + Vector2 fromTarget = (NPC.Center - Target.Center).SafeNormalize(Vector2.UnitX); + Vector2 goalPos = Target.Center + (fromTarget * dist) - (Vector2.UnitY * 32); + if (NPC.DistanceSQ(goalPos) <= 2048) + NPC.velocity *= 0.9f; + else if (NPC.velocity.LengthSquared() < 16f) //7.5^2 + NPC.velocity += NPC.DirectionTo(goalPos).SafeNormalize(Vector2.Zero) * 0.1f; + else + NPC.velocity = NPC.DirectionTo(goalPos).SafeNormalize(Vector2.Zero) * 4f; + } + #endregion + + #region Scythe Movement + Attack + else + { + if (Time < CrimsonEyeAttackIdleDuration) + NPC.velocity *= 0.9f; + if (Time >= CrimsonEyeAttackIdleDuration + CrimsonEyeAttackSetUpDuration && Time < CrimsonEyeAttackDuration) + { + if (Time == CrimsonEyeAttackIdleDuration + CrimsonEyeAttackSetUpDuration) + NPC.velocity = NPC.DirectionTo(Target.Center); + + bool onSurface = Target.Center.Y / 16f < Main.worldSurface; + float speed = onSurface ? 10f : 8f; + if (Time < CrimsonEyeAttackIdleDuration + CrimsonEyeAttackSetUpDuration + CrimsonEyeAttackBuildUpDuration) + { + float lerp = CalamityUtils.SineInEasing((Time - (CrimsonEyeAttackIdleDuration + CrimsonEyeAttackSetUpDuration)) / CrimsonEyeAttackBuildUpDuration, 1); + speed = MathHelper.Lerp(0f, speed, lerp); + } + + float turnAmt = TurnAccelerationMultiplier * ((NPC.Distance(Target.Center) - TurnAccelerationDistanceBuffer) / TurnAccelerationDistanceDivisor); + + NPC.velocity = NPC.velocity.RotateDirectionTowards(NPC.AngleTo(Target.Center), turnAmt) * speed; + } + else + { + NPC.velocity *= 0.9f; + + if (Time == CrimsonEyeAttackDuration) + { + foreach (Projectile p in Main.ActiveProjectiles) + { + if (p.type != ModContent.ProjectileType()) + continue; + + p.timeLeft = 60; + } + } + + if (Time > CrimsonEyeAttackDuration + CrimsonEyeAttackEndDuration) + SetupForNextAttack(); + } + + if (Time == CrimsonEyeAttackIdleDuration) + { + SoundStyle explosion = new("CalamityMod/Sounds/Custom/Ravager/RavagerMissileExplosion"); + explosion.Volume = 0.5f; + + SoundEngine.PlaySound(explosion, NPC.Center); + if (Main.netMode != NetmodeID.MultiplayerClient) + { + float projCount = 10; + for (int i = 0; i < projCount; i++) + Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, Vector2.Zero, ModContent.ProjectileType(), BloodScytheDamage, 0.5f, -1, MathHelper.TwoPi / projCount * i); + } + } + } + #endregion + } + #endregion + } + + private void IllusionDash() + { + #region Attack Start + if (Time < IllusionDashTeleportDuration) + { + if (Time == 0) + { + AttackPosition = Target.Center; + AttackRotation = Main.rand.NextFloat(0, MathHelper.TwoPi); + NPC.netUpdate = true; + } + + TeleportDuration = IllusionDashTeleportDuration; + + if (Time < (TeleportDuration / 2f)) + { + if (Time % 4 == 0) + { + Vector2 startPoint = NPC.Center; + + for (int i = 0; i < (CalamityWorld.death ? 8 : 4); i++) + { + Vector2 myEndPoint = AttackPosition + ((AttackRotation + (CalamityWorld.death ? MathHelper.PiOver4 : MathHelper.PiOver2) * i).ToRotationVector2() * IllusionDashTeleportDistance); + Vector2 direction = myEndPoint - startPoint; + + float curveIntensity = Main.rand.NextFloat(-0.2f, 0.2f); + Vector2 perpindicular = direction.RotatedBy(MathHelper.PiOver2); + + Vector2 controlPoint1 = startPoint + (direction * 0.25f) + (perpindicular * curveIntensity); + Vector2 controlPoint2 = startPoint + (direction * 0.75f) + (perpindicular * curveIntensity); + + BezierCurve path = new BezierCurve(startPoint, controlPoint1, controlPoint2, myEndPoint); + + BrainOfCthulhuAfterImage afterimage = new(path, NPC.rotation, Vector2.One, (int)((TeleportDuration * 0.75f) - Time), BoCFrame); + BoCAfterImages.Add(afterimage); + GeneralParticleHandler.SpawnParticle(afterimage); + } + } + TeleportTime++; + } + else if (Time == (TeleportDuration / 2f) && !AttackFlag) + { + AttackFlag = true; + + for (int i = 0; i < (CalamityWorld.death ? 8 : 4); i++) + { + 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, BrainIllusionDamage, 30, rot).netUpdate = true; + } + + NPC.netUpdate = true; + } + else + TeleportTime--; + + NPC.Opacity = 1 - (TeleportTime / (TeleportDuration / 2f)); + } + #endregion + else + { + float startTime = Time - IllusionDashTeleportDuration; + + if (startTime == 0) + { + AttackPosition = NPC.Center; + TeleportTime = 0; + AttackFlag = false; + + BoCAfterImages = []; + NPC.Opacity = 1f; + + GenericSparkle sparkle = new(NPC.Center, Vector2.Zero, Color.Yellow, Color.Orange, 2f, 12, needed: true); + GeneralParticleHandler.SpawnParticle(sparkle); + + NPC.netUpdate = true; + + foreach (NPC n in Main.ActiveNPCs) + if (n.type == ModContent.NPCType()) + n.netUpdate = true; + } + if (startTime < 30) + { + float lerp = startTime / 30f; + 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) + { + float reelBackSpeedExponent = 2.6f; + float reelBackCompletion = Utils.GetLerpValue(0f, 30, startTime - 130, true); + float reelBackSpeed = MathHelper.Lerp(2.5f, 16f, MathF.Pow(reelBackCompletion, reelBackSpeedExponent)); + Vector2 reelBackVelocity = (AttackRotation + MathHelper.Pi).ToRotationVector2() * -reelBackSpeed; + NPC.velocity = Vector2.Lerp(NPC.velocity, reelBackVelocity, 0.25f); + } + else if (startTime <= 30 + IllusionDashSpinDuration + 30 + IllusionDashFakeoutTeleportDuration) //176 + { + NPC.velocity = Vector2.Zero; + + if (startTime == 30 + IllusionDashSpinDuration + 30) + { + AttackPosition = Target.Center; + AttackRotation = AttackRotation + MathHelper.Pi + Main.rand.NextFloat(-MathHelper.PiOver2, MathHelper.PiOver2); + NPC.netUpdate = true; + } + + float wrappedCounter = startTime - (30 + IllusionDashSpinDuration + 30); + + TeleportDuration = IllusionDashFakeoutTeleportDuration; + + Vector2 endPoint = AttackPosition + (AttackRotation.ToRotationVector2() * 270); + + if (wrappedCounter < (TeleportDuration / 2f)) + { + if (wrappedCounter % 2 == 0) + { + Vector2 startPoint = NPC.Center; + + Vector2 direction = endPoint - startPoint; + + float curveIntensity = Main.rand.NextFloat(-0.2f, 0.2f); + Vector2 perpindicular = direction.RotatedBy(MathHelper.PiOver2); + + Vector2 controlPoint1 = startPoint + (direction * 0.25f) + (perpindicular * curveIntensity); + Vector2 controlPoint2 = startPoint + (direction * 0.75f) + (perpindicular * curveIntensity); + + BezierCurve path = new BezierCurve(startPoint, controlPoint1, controlPoint2, endPoint); + + BrainOfCthulhuAfterImage afterimage = new(path, NPC.rotation, Vector2.One, (int)((TeleportDuration * 0.75f) - wrappedCounter), BoCFrame); + BoCAfterImages.Add(afterimage); + GeneralParticleHandler.SpawnParticle(afterimage); + } + TeleportTime++; + } + else if (wrappedCounter == (int)(TeleportDuration / 2f) && !AttackFlag) + { + AttackFlag = true; + NPC.Center = endPoint; + DisableMultiplayerSmoothing = true; + } + else + { + TeleportTime--; + if (TeleportTime <= 0) + { + TeleportTime = 0; + BoCAfterImages = []; + ResetAttackValues(); + NPC.Opacity = 1f; + NPC.netUpdate = true; + AttackRotation = NPC.AngleTo(Target.Center); + } + } + + NPC.Opacity = 1 - (TeleportTime / (TeleportDuration / 2f)); + } + else if (startTime < 90 + IllusionDashSpinDuration + 30 + IllusionDashFakeoutTeleportDuration + 30) + { + NPC.velocity *= 0.9f; + if (startTime % 15 == 0) + { + for (int i = 0; i < 2; i++) + { + Vector2 dir = NPC.DirectionTo(Target.Center); + if (Main.netMode != NetmodeID.MultiplayerClient) + { + Vector2 initialDir = dir.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 4f, MathHelper.Pi / 4f)); + Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, initialDir * Main.rand.NextFloat(10f, 25f), ProjectileID.BloodNautilusShot, BloodShotDamage, 0.5f, ai0: dir.ToRotation() + MathHelper.TwoPi, ai1: initialDir.ToRotation()); + } + NPC.velocity -= dir * 2f; + } + } + } + else if (startTime >= 135 + IllusionDashSpinDuration + 30 + IllusionDashFakeoutTeleportDuration + 30) + { + foreach (NPC n in Main.ActiveNPCs) + if (n.type == ModContent.NPCType()) + n.active = false; + + SetupForNextAttack(); + } + } + } + + private void IllusionTrick() + { + if (Time >= 90) + { + if (Time == 90) + { + foreach (Projectile p in Main.ActiveProjectiles) + { + if (!p.friendly) + continue; + + p.Calamity().IgnoreBoCIllusions = true; + } + + int brainAngleSlot = Main.rand.Next(0, IllusionTrickAngleGroups); + int brainDistSlot = Main.rand.Next(0, IllusionTrickGroupSize); + + if (Main.netMode != NetmodeID.MultiplayerClient) + for (int a = 0; a < IllusionTrickAngleGroups; a++) + for (int d = 0; d < IllusionTrickGroupSize; d++) + { + if (a != brainAngleSlot || d != brainDistSlot) + NPC.NewNPC(NPC.GetSource_FromThis(), 0, 0, ModContent.NPCType(), 0, MathHelper.TwoPi / IllusionTrickAngleGroups * a, FalseBrain.TimeDivisor / IllusionTrickGroupSize * d); + } + + AttackTime = (int)(FalseBrain.TimeDivisor / IllusionTrickGroupSize * brainDistSlot); + AttackRotation = MathHelper.TwoPi / IllusionTrickAngleGroups * brainAngleSlot; + AttackFlag = false; + AttackPosition = Target.Center; + + NPC.ShowNameOnHover = false; + NPC.netUpdate = true; + } + + NPC.damage = 0; + + if (AttackFlag) + { + if (AttackCounter == 0) + { + NPC.ShowNameOnHover = true; + NPC.velocity = NPC.DirectionFrom(Target.Center) * 8f; + } + else + NPC.velocity *= 0.95f; + + if (AttackCounter >= IllusionTrickStunDuration) + { + NPC.damage = NPC.defDamage; + SetupForNextAttack(); + NPC.Opacity = 1f; + TeleportTime = 0; + return; + } + + AttackCounter++; + } + else if (Time >= IllusionTrickTimeLimit) //Players have failed to find the real BoC within the time limit + { + if (Time == IllusionTrickTimeLimit) + { + foreach (Player p in Main.ActivePlayers) + { + if (p.Distance(NPC.Center) > DespawnRange) + continue; + + AttackList.Add((byte)p.whoAmI); + } + + foreach (NPC n in Main.ActiveNPCs) + { + if (n.type != ModContent.NPCType()) + continue; + + n.ModNPC().BeenHit = true; + } + + for (int i = 1; i <= 3; i++) + { + Color color = i switch + { + 1 => Color.Yellow, + 2 => Color.Orange, + _ => Color.Red, + }; + PulseRing ring = new(NPC.Center, NPC.velocity * 0.5f, color, 0f, 1f + i * 0.5f, 24); + GeneralParticleHandler.SpawnParticle(ring); + } + } + else if (Time % 30 == 0) + { + if (AttackList.Count > 0) + { + if (Main.netMode != NetmodeID.MultiplayerClient) + Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, Vector2.Zero, ModContent.ProjectileType(), 0, 0f, -1, AttackList[0], 2f); + AttackList.RemoveAt(0); + } + else + { + Vector2 direction = Target.velocity.SafeNormalize(Vector2.UnitX * Target.direction).RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 3f, MathHelper.Pi / 3f)); + float distance = DefaultTeleportDistance; + AttackPosition = Target.Center + (direction * distance); + BoCAfterImages = []; + NPC.Opacity = 1f; + TeleportTime = 0; + Time = ChaseTime - 1; + NPC.damage = NPC.defDamage; + NPC.netUpdate = true; + ResetAttackValues(); + + AIState = BrainAIState.Phase2Idle; + } + } + } + else + { + CachedRatio = (float)Math.Cos(AttackTime * MathHelper.TwoPi / FalseBrain.TimeDivisor); + + float lerp = CalamityUtils.SineInOutEasing(MathHelper.Clamp((Time - 150) / 30f, 0f, 1f), 1); + float baseDist = 240; + float circleDist = 480; + if (Time - 150 < 30f) + { + baseDist = MathHelper.Lerp(480, 240, lerp); + circleDist = MathHelper.Lerp(240, 480, lerp); + } + 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; + } + } + else if (Time <= 60) + { + TeleportDuration = 60; + TeleportTime++; + NPC.Opacity = 1 - (Time / 60f); + + if (Time < 50) + { + Vector2 startPoint = NPC.Center; + Vector2 endPoint = NPC.Center + Vector2.UnitX.RotatedBy(Main.rand.NextFloat(0, MathHelper.TwoPi)) * Main.rand.NextFloat(240, 480); + + Vector2 direction = endPoint - startPoint; + float curveIntensity = Main.rand.NextFloat(-0.2f, 0.2f); + Vector2 perpindicular = direction.RotatedBy(MathHelper.PiOver2); + + Vector2 controlPoint1 = startPoint + (direction * 0.25f) + (perpindicular * curveIntensity); + Vector2 controlPoint2 = startPoint + (direction * 0.75f) + (perpindicular * curveIntensity); + + BezierCurve path = new BezierCurve(startPoint, controlPoint1, controlPoint2, endPoint); + + BrainOfCthulhuAfterImage afterimage = new(path, NPC.rotation, Vector2.One, (int)(60 - Time), BoCFrame); + BoCAfterImages.Add(afterimage); + GeneralParticleHandler.SpawnParticle(afterimage); + } + } + else + { + NPC.Opacity = 0f; + BoCAfterImages = []; + } + + if (Time >= 180) + AttackTime++; + else if (Time >= 150) + AttackTime += (Time - 150) / 30f; + } + + #endregion + + private void DeathAnimation() + { + if (Time == 0) + NPC.velocity = NPC.DirectionFrom(Target.Center) * 6f; + else + NPC.velocity *= 0.95f; + + NPC.rotation = MathHelper.Pi / 24f * NPC.oldVelocity.X; + TeleportTime *= 0.6f; + if (TeleportTime < 0.005f) + TeleportTime = 0; + BoCDrawOffset *= 0.6f; + NPC.Opacity = BringOpacityTo(NPC.Opacity, 1, 0.1f); + + (float angle, Vector2 offset, int time)[] bloodGushingData = [ + (MathHelper.Pi / 6f, new(18, 12), 90), + (MathHelper.Pi, new(-30, -10), 150), + (-MathHelper.Pi / 4f, new(20, -40), 180), + (MathHelper.Pi + MathHelper.Pi / 4f, new(-20, -40), 200), + (MathHelper.Pi / 1.75f, new(-5, 22), 210) + ]; + + for (int i = 0; i < bloodGushingData.Length; i++) + { + if (Time >= bloodGushingData[i].time) + { + if (Time == bloodGushingData[i].time) + { + Vector2 bloodDir = bloodGushingData[i].angle.ToRotationVector2(); + BloodParticle2 p2 = new(NPC.Center + bloodGushingData[i].offset.RotatedBy(NPC.rotation), bloodDir * 7.5f, 16, 0.5f, Color.Red); + GeneralParticleHandler.SpawnParticle(p2); + NPC.velocity = bloodDir * -4f; + + SoundStyle explosion = new("CalamityMod/Sounds/Custom/Ravager/RavagerMissileExplosion") + { + Volume = 0.5f, + Pitch = i / (float)(bloodGushingData.Length - 1) + }; + SoundEngine.PlaySound(explosion, NPC.Center); + + Main.LocalPlayer.SetScreenshake(1f); + } + + for (int j = 0; j < 2; j++) + { + BloodParticle p = new(NPC.Center + bloodGushingData[i].offset.RotatedBy(NPC.rotation), (bloodGushingData[i].angle + Main.rand.NextFloat(-MathHelper.Pi / 10f, MathHelper.Pi / 10f)).ToRotationVector2() * Main.rand.NextFloat(5f, 10f), 32, 1f, Color.Red); + GeneralParticleHandler.SpawnParticle(p); + } + } + + } + + if (Time >= 215) + { + SoundStyle explosion = new("CalamityMod/Sounds/Custom/Ravager/RavagerMissileExplosion"); + SoundEngine.PlaySound(explosion, NPC.Center); + + Main.LocalPlayer.SetScreenshake(2f); + + int pCount = 10; + for (int i = 0; i < pCount; i++) + { + float initalSpeed = 24f; + Vector2 pVelo = Vector2.UnitX.RotatedBy(MathHelper.TwoPi / pCount * i) * initalSpeed; + + for (int j = 0; j < 2; j++) + { + BloodParticle p = new(NPC.Center, pVelo.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 6f, MathHelper.Pi / 6f)) * Main.rand.NextFloat(0.5f, 1f), 32, 1f, Color.Red); + GeneralParticleHandler.SpawnParticle(p); + } + BloodParticle2 p2 = new(NPC.Center, pVelo * 0.75f, 16, 0.5f, Color.Red); + GeneralParticleHandler.SpawnParticle(p2); + } + + NPC.dontTakeDamage = false; + if (Main.netMode != NetmodeID.MultiplayerClient) + NPC.StrikeInstantKill(); + } + + float animationCompletion = Time / 215f; + NPC.frameCounter += 2 * animationCompletion; + + if (Main.rand.NextFloat(0.5f, 1f) < animationCompletion) + { + Vector2 edgeBloodDir = Main.rand.NextVector2CircularEdge(1, 1); + BloodParticle b = new(NPC.Center + (edgeBloodDir * NPC.Size * 0.75f), edgeBloodDir.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 10f, MathHelper.Pi / 10f)) * Main.rand.NextFloat(2f, 4f), 16, 0.75f, Color.Red); + GeneralParticleHandler.SpawnParticle(b); + } + } + + #endregion + + public override void SendExtraAI(BitWriter bitWriter, BinaryWriter binaryWriter) + { + binaryWriter.Write((byte)PreviousAttack); + + if (AIState == BrainAIState.Stunned || AIState >= BrainAIState.Phase2TransitionClosed) + { + binaryWriter.Write(TeleportTime); + binaryWriter.Write(TeleportDuration); + } + + if (AIState <= BrainAIState.SurfaceSpawnAnimation) + { + binaryWriter.Write(SpawnTime); + binaryWriter.Write(SpawnDelay); + } + + binaryWriter.Write(CachedRatio); + + binaryWriter.WriteFlags(OnSecondCreeperPhase, isNegative, AttackFlag); + + binaryWriter.Write(AttackRotation); + binaryWriter.Write(AttackTime); + binaryWriter.Write(AttackCounter); + + binaryWriter.WritePackedWorldPosition(AttackPosition); + + binaryWriter.Write((byte)availableAttacks.Count); + + 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.ReadByte(); + + if (AIState == BrainAIState.Stunned || AIState >= BrainAIState.Phase2TransitionClosed) + { + TeleportTime = binaryReader.ReadSingle(); + TeleportDuration = binaryReader.ReadSingle(); + } + + if (AIState <= BrainAIState.SurfaceSpawnAnimation) + { + SpawnTime = binaryReader.ReadSingle(); + SpawnDelay = binaryReader.ReadInt32(); + } + + CachedRatio = binaryReader.ReadSingle(); + + binaryReader.ReadFlags(out OnSecondCreeperPhase, out isNegative, out AttackFlag); + + AttackRotation = binaryReader.ReadSingle(); + AttackTime = binaryReader.ReadSingle(); + AttackCounter = binaryReader.ReadInt32(); + + AttackPosition = binaryReader.ReadPackedWorldPosition(); + + int availableLength = binaryReader.ReadByte(); + availableAttacks = binaryReader.ReadBytes(availableLength).Select(e => (BrainAIState)e).ToList(); + + byte attackLength = binaryReader.ReadByte(); + AttackList = binaryReader.ReadBytes(attackLength).ToList(); + } + + public override bool? CanBeHitByProjectile(Mod mod, Projectile projectile) + { + if (AIState == BrainAIState.IllusionTrick && !AttackFlag && projectile.Calamity().IgnoreBoCIllusions) + return false; + return base.CanBeHitByProjectile(mod, projectile); + } + + public override void ModifyHitByItem(Mod mod, Player player, Item item, ref NPC.HitModifiers modifiers) + { + if (AIState != BrainAIState.DeathAnimation) + modifiers.SetMaxDamage(NPC.life - 1); + } + + public override void ModifyHitByProjectile(Mod mod, Projectile projectile, ref NPC.HitModifiers modifiers) + { + if (AIState != BrainAIState.DeathAnimation) + modifiers.SetMaxDamage(NPC.life - 1); + } + + public override void HitEffect(Mod mod, NPC.HitInfo hit) + { + if (AIState != BrainAIState.DeathAnimation && (NPC.life + 1) <= hit.Damage) + { + NPC.life = 1; + NPC.BossBar = null; + NPC.dontTakeDamage = true; + + if (AIState == BrainAIState.Stunned) + TeleportTime = 0; + + 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) => AIState == BrainAIState.DeathAnimation && !NPC.dontTakeDamage; + + public override void FindFrame(Mod mod, int frameHeight) + { + if (BoCFrame == Rectangle.Empty) + BoCFrame = TextureAssets.Npc[NPCID.BrainofCthulhu].Frame(verticalFrames: 8); + + if (NPC.frameCounter == 0) + BoCFrame.Y += frameHeight; + + if (AIState <= BrainAIState.Phase2TransitionClosed) + { + if (BoCFrame.Y > frameHeight * 3) + BoCFrame.Y = 0; + return; + } + if (BoCFrame.Y < frameHeight * 4) + BoCFrame.Y = frameHeight * 4; + + if (BoCFrame.Y > frameHeight * 7) + BoCFrame.Y = frameHeight * 4; + } + + public override bool PreDraw(Mod mod, SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) + { + bool phase1 = AIState < BrainAIState.Phase2TransitionClosed; + bool drawBrain = true; + + if (phase1) + { + List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper).ToList(); + creepers.Sort((a, b) => b.DistanceSQ(NPC.Center).CompareTo(a.DistanceSQ(NPC.Center))); + + int c = 0; + foreach (NPC creeper in creepers) + { + List curvePoints = BrainOfCthulhuSystem.VerletTendrils[creeper.AIOverride().CreeperID]; + if (curvePoints is null) + continue; + + float glowIntensity = creeper.AIOverride().ConnectionOpacity; + Color ichorLess = Color.Lerp(Color.Transparent, Color.OrangeRed * 0.333f, glowIntensity); + Color ichorful = Color.Lerp(Color.OrangeRed * 0.25f, Color.Orange * 0.666f, glowIntensity); + + for (int i = 0; i < curvePoints.Count; i++) + { + Vector2 start = curvePoints[i].position; + Vector2 end = i == curvePoints.Count - 1 ? creeper.Center : curvePoints[i + 1].position; + Vector2 center = (end + start) / 2f; + start -= Main.screenPosition; + end -= Main.screenPosition; + + float rotation = (end - start).ToRotation() - MathHelper.PiOver2; + + float flowTime = creeper.AIOverride().FlowTime; + float flowAmt = creeper.AIOverride().FlowAmount; + float ichorRatio = CalamityUtils.ExpInEasing((float)Math.Sin((flowTime + (i * flowAmt)) * 2f) / 2f + 0.5f, 1); + + Color glowColor = Color.Lerp(ichorLess, ichorful, ichorRatio); + + float dist = Vector2.Distance(start, end); + Vector2 tendrilScale = new(1f + (0.5f * (ichorRatio * (1 + (glowIntensity * 0.5f)))), dist / BrainOfCthulhuSystem.tendril.Height()); + + spriteBatch.Draw(BrainOfCthulhuSystem.tendril.Value, start, null, Lighting.GetColor(center.ToTileCoordinates()) * NPC.Opacity, rotation, BrainOfCthulhuSystem.tendril.Size() * Vector2.UnitX * 0.5f, tendrilScale, SpriteEffects.None, 0f); + spriteBatch.Draw(BrainOfCthulhuSystem.GetTendrilGlow(), start, null, glowColor * NPC.Opacity, rotation, BrainOfCthulhuSystem.GetTendrilGlow().Size() * Vector2.UnitX * 0.5f, tendrilScale, SpriteEffects.None, 0f); + } + + c++; + } + + foreach (NPC creeper in creepers) + { + float glowIntensity = creeper.AIOverride().ConnectionOpacity; + + spriteBatch.Draw(BrainOfCthulhuSystem.GetCreeperGlow(), creeper.Center - Main.screenPosition, null, Color.Orange * glowIntensity, creeper.rotation, TextureAssets.Npc[NPCID.Creeper].Size() * 0.5f, creeper.scale * 1.15f, 0, 0); + + spriteBatch.Draw(TextureAssets.Npc[NPCID.Creeper].Value, creeper.Center - Main.screenPosition, null, Lighting.GetColor(creeper.Center.ToTileCoordinates()).MultiplyRGB(Color.Lerp(Color.White, new Color(255, 180, 180), glowIntensity)), creeper.rotation, TextureAssets.Npc[NPCID.Creeper].Size() * 0.5f, creeper.scale, 0, 0); + } + } + else + { + List falseBrains = Main.npc.Where(n => n.active && n.type == ModContent.NPCType()).ToList(); + if (falseBrains.Count > 0) + { + drawBrain = false; + + falseBrains.Add(NPC); + falseBrains.Sort((a, b) => + { + float aValue; + float bValue; + + if (a.ModNPC is FalseBrain falseA) + aValue = falseA.DrawPriority; + else + aValue = a.AIOverride().CachedRatio; + + if (b.ModNPC is FalseBrain falseB) + bValue = falseB.DrawPriority; + else + bValue = b.AIOverride().CachedRatio; + + return aValue.CompareTo(bValue); + }); + + foreach (NPC n in falseBrains) + { + if (n.ModNPC is FalseBrain falseBrain) + falseBrain.DrawSelf(spriteBatch, screenPos, Lighting.GetColor(n.Center.ToTileCoordinates())); + else + DrawBrainLikeFakes(spriteBatch, n); + } + } + } + + if (drawBrain) + DrawBrain(spriteBatch, NPC); + + return false; + } + + internal static float BringOpacityTo(float currentOpacity, float goalOpacity, float changeAmount = 0.025f) + { + if (currentOpacity == goalOpacity) + return goalOpacity; + + if (currentOpacity < goalOpacity) + { + currentOpacity += changeAmount; + if (currentOpacity >= goalOpacity) + return goalOpacity; + else + return currentOpacity; + } + else + { + currentOpacity -= changeAmount; + if (currentOpacity <= goalOpacity) + return goalOpacity; + else + return currentOpacity; + } + } + + private static void DrawBrain(SpriteBatch spriteBatch, NPC brain) + { + BrainOfCthulhuAI ai = brain.AIOverride(); + bool phase1 = ai.AIState < BrainAIState.Phase2TransitionClosed; + + Vector2 drawPos = brain.Center + ai.BoCDrawOffset + (Vector2.UnitY * 16) - Main.screenPosition; + Vector2 scale = Vector2.One; + + if (!phase1 && ai.TeleportTime != 0) + { + ai.BoCAfterImages.RemoveAll(p => p.Time > p.Lifetime); + foreach (Particle p in ai.BoCAfterImages) + p.CustomDraw(spriteBatch); + + //Color glowColor = Color.White * (teleportCounter / 30f); + scale = Vector2.Lerp(Vector2.One, new Vector2(0.5f + ((float)Math.Cos(ai.Time / (ai.TeleportDuration / 2f) * MathHelper.TwoPi) / 2f + 0.5f), 0.5f + ((float)Math.Sin(ai.Time / (ai.TeleportDuration / 2f) * MathHelper.TwoPi) / 2f + 0.5f)), CalamityUtils.SineInOutEasing(ai.TeleportTime / (ai.TeleportDuration / 2f), 1)); + + spriteBatch.Draw(TextureAssets.Npc[NPCID.BrainofCthulhu].Value, drawPos, ai.BoCFrame, Lighting.GetColor(brain.Center.ToTileCoordinates()) * brain.Opacity, brain.rotation, ai.BoCFrame.Size() * 0.5f, scale * brain.scale, 0, 0); + //spriteBatch.Draw(GetBrainGlow(), drawPos, NPC.frame, glowColor, NPC.rotation, NPC.frame.Size() * 0.5f, scale, 0, 0); + } + else + spriteBatch.Draw(TextureAssets.Npc[NPCID.BrainofCthulhu].Value, drawPos, ai.BoCFrame, Lighting.GetColor(brain.Center.ToTileCoordinates()) * brain.Opacity, brain.rotation, ai.BoCFrame.Size() * 0.5f, scale * brain.scale, 0, 0); + } + + private static void DrawBrainLikeFakes(SpriteBatch spriteBatch, NPC brain) + { + BrainOfCthulhuAI ai = brain.AIOverride(); + + Vector2 scaleDistort = new Vector2((float)Math.Cos(Main.GlobalTimeWrappedHourly * MathHelper.TwoPi * 2) / 2f, (float)Math.Sin(Main.GlobalTimeWrappedHourly * MathHelper.TwoPi * 2) / 2f); + + int spawnTime = 150 - ((int)ai.Time); + float startLerp = spawnTime / 60f; + + Color drawColor = Lighting.GetColor(brain.Center.ToTileCoordinates()); + + if (spawnTime > 0) + { + drawColor *= (1 - startLerp); + scaleDistort *= startLerp; + } + else + scaleDistort = Vector2.Zero; + + spriteBatch.Draw(TextureAssets.Npc[NPCID.BrainofCthulhu].Value, brain.Center + (Vector2.UnitY * 16) - Main.screenPosition, ai.BoCFrame, drawColor, brain.rotation, ai.BoCFrame.Size() * 0.5f, (Vector2.One + scaleDistort) * brain.scale, 0, 0); + } + + private void SetupForNextAttack() + { + Player target = Main.player[NPC.target]; + + Vector2 direction = target.velocity.SafeNormalize(Vector2.UnitX * target.direction).RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 3f, MathHelper.Pi / 3f)); + float distance = DefaultTeleportDistance; + AttackPosition = target.Center + (direction * distance); + BoCAfterImages = []; + Time = ChaseTime - 1; + ResetAttackValues(); + NPC.netUpdate = true; + + if (availableAttacks.Count != 0) + { + if (availableAttacks[0] != BrainAIState.Phase2Idle) + AttackCounter = 4; + else + availableAttacks.RemoveAt(0); + } + + AIState = BrainAIState.Phase2Idle; + } + + private void ResetAttackValues() + { + isNegative = false; + AttackRotation = 0; + AttackTime = 0; + AttackFlag = false; + AttackPosition = Vector2.Zero; + AttackCounter = 0; + } + + public static int GetBrainOfCthuluCreepersCountRevDeath() => CalamityWorld.death ? 30 : 21; +} diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuSystem.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuSystem.cs new file mode 100644 index 0000000000..a4cc06eb76 --- /dev/null +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuSystem.cs @@ -0,0 +1,313 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.DataStructures; +using CalamityMod.World; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using ReLogic.Content; +using Terraria; +using Terraria.Audio; +using Terraria.GameContent; +using Terraria.Graphics.Effects; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses.BrainOfCthulhu; + +public class BrainOfCthulhuSystem : ModSystem +{ + internal static Asset tendril; + private static Texture2D tendrilGlow = null; + private static Texture2D brainGlow = null; + private static Texture2D creeperGlow = null; + + internal static float ScreenBlurStrength = 0f; + + internal static List[] VerletTendrils = new List[BrainOfCthulhuAI.GetBrainOfCthuluCreepersCountRevDeath()]; + + private static int previousMusic = -1; + public static int PreviousMusic => previousMusic; + + public override void OnModLoad() + { + if (!Main.dedServ) + { + tendril = ModContent.Request("Terraria/Images/Chain12"); + } + + On_NPC.SpawnBoss += SpawnBrainNoMessage; + On_Player.ItemCheck_UseBossSpawners += BlockRoar; + On_Main.UpdateAudio_DecideOnNewMusic += StopBoss3FromStarting; + On_Main.UpdateAudio_DecideOnTOWMusic += StopOWBoss1FromStarting; + } + + private void StopBoss3FromStarting(On_Main.orig_UpdateAudio_DecideOnNewMusic orig, Main self) + { + orig(self); + + 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; + + // 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)) + { + if (Main.newMusic == MusicID.Boss3) + Main.newMusic = previousMusic; + + if (Main.curMusic == MusicID.Boss3) + Main.curMusic = previousMusic; + } + } + + private void StopOWBoss1FromStarting(On_Main.orig_UpdateAudio_DecideOnTOWMusic orig, Main self) + { + orig(self); + + if (NPC.crimsonBoss == -1 || !CalamityWorld.revenge) + 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)) + { + if (Main.newMusic == MusicID.OtherworldlyBoss1) + Main.newMusic = previousMusic; + + if (Main.curMusic == MusicID.OtherworldlyBoss1) + Main.curMusic = previousMusic; + } + } + + private void BlockRoar(On_Player.orig_ItemCheck_UseBossSpawners orig, Player self, int onWhichPlayer, Item sItem) + { + if (sItem.type != ItemID.BloodySpine || !CalamityWorld.revenge || !self.ItemTimeIsZero || self.itemAnimation <= 0) + { + orig(self, onWhichPlayer, sItem); + return; + } + + SoundEngine.PlaySound(SoundID.NPCDeath1, Main.LocalPlayer.Center); + + if (self.ZoneCrimson) + { + self.ApplyItemTime(sItem); + CalamityUtils.SpawnBossUsingItem(self, NPCID.BrainofCthulhu); + } + } + + private void SpawnBrainNoMessage(On_NPC.orig_SpawnBoss orig, int spawnPositionX, int spawnPositionY, int Type, int targetPlayerIndex) + { + if (Type != NPCID.BrainofCthulhu || !CalamityWorld.revenge) + { + orig(spawnPositionX, spawnPositionY, Type, targetPlayerIndex); + return; + } + + int num = NPC.NewNPC(NPC.GetBossSpawnSource(targetPlayerIndex), spawnPositionX, spawnPositionY, Type, 1); + + if (num == 200 || num == -1) + return; + + if (Main.player[targetPlayerIndex].HeldItem.type == ItemID.BloodySpine) + BrainOfCthulhuAI.SummonedViaItem = true; + + NPC.crimsonBoss = num; + Main.npc[num].target = targetPlayerIndex; + Main.npc[num].timeLeft *= 20; + + previousMusic = Main.curMusic; + + if (Main.netMode == NetmodeID.Server && num < 200) + NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, num); + } + + internal static Texture2D GetTendrilGlow() + { + if (tendrilGlow == null) + { + var tex = new Texture2D(Main.graphics.GraphicsDevice, tendril.Value.Width, tendril.Value.Height); + + var BaseArray = new Color[tex.Width * tex.Height]; + var ColorArray = new Color[tex.Width * tex.Height]; + tendril.Value.GetData(BaseArray); + for (var i = 0; i < BaseArray.Length; i++) + { + ColorArray[i] = new Color(255, 255, 255) * (((float)BaseArray[i].A) / 255f); + } + tex.SetData(ColorArray); + tendrilGlow = tex; + } + return tendrilGlow; + } + + internal static Texture2D GetBrainGlow() + { + if (brainGlow == null) + { + var tex = new Texture2D(Main.graphics.GraphicsDevice, TextureAssets.Npc[NPCID.BrainofCthulhu].Value.Width, TextureAssets.Npc[NPCID.BrainofCthulhu].Value.Height); + + var BaseArray = new Color[tex.Width * tex.Height]; + var ColorArray = new Color[tex.Width * tex.Height]; + TextureAssets.Npc[NPCID.BrainofCthulhu].Value.GetData(BaseArray); + for (var i = 0; i < BaseArray.Length; i++) + { + ColorArray[i] = new Color(255, 255, 255) * (((float)BaseArray[i].A) / 255f); + } + tex.SetData(ColorArray); + brainGlow = tex; + } + return brainGlow; + } + + internal static Texture2D GetCreeperGlow() + { + if (creeperGlow == null) + { + var tex = new Texture2D(Main.graphics.GraphicsDevice, TextureAssets.Npc[NPCID.Creeper].Value.Width, TextureAssets.Npc[NPCID.Creeper].Value.Height); + + var BaseArray = new Color[tex.Width * tex.Height]; + var ColorArray = new Color[tex.Width * tex.Height]; + TextureAssets.Npc[NPCID.Creeper].Value.GetData(BaseArray); + for (var i = 0; i < BaseArray.Length; i++) + { + ColorArray[i] = new Color(255, 255, 255) * (((float)BaseArray[i].A) / 255f); + } + tex.SetData(ColorArray); + creeperGlow = tex; + } + return creeperGlow; + } + + public override void PostUpdateNPCs() + { + if (!NPC.AnyNPCs(NPCID.BrainofCthulhu)) + BrainOfCthulhuAI.SummonedViaItem = false; + + if (Main.netMode != NetmodeID.Server) + { + if (NPC.crimsonBoss != -1 && CalamityWorld.revenge && Main.npc[NPC.crimsonBoss].ai[0] < (float)BrainOfCthulhuAI.BrainAIState.Phase2TransitionClosed) + { + List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper).ToList(); + + foreach (NPC creeper in creepers) + { + int creeperID = (int)creeper.ai[0]; + + Vector2 startPoint = Main.npc[NPC.crimsonBoss].Center + Vector2.UnitY * 32; + + float creeperRatio = creeperID / (float)BrainOfCthulhuAI.GetBrainOfCthuluCreepersCountRevDeath(); + if (creeperID % 2 == 0) + startPoint += new Vector2(MathHelper.Lerp(-24, 0, creeperRatio), 0); + else + startPoint += new Vector2(MathHelper.Lerp(24, 0, creeperRatio), 0); + + Vector2 endPoint = creeper.Center; + + List tendril = VerletTendrils[creeperID]; + if (tendril is null || tendril.Count == 0) + continue; + + tendril[0].position = startPoint; + tendril[0].locked = true; + tendril[^1].position = endPoint; + tendril[^1].locked = true; + + VerletSimulatedSegment.SimpleSimulation(tendril, 16, 10, 3); + } + } + } + } + + public override void PostDrawTiles() + { + if (Main.netMode != NetmodeID.Server) + { + if (NPC.crimsonBoss == -1 || !CalamityWorld.revenge || Main.npc[NPC.crimsonBoss].ai[0] >= (float)BrainOfCthulhuAI.BrainAIState.Phase2TransitionClosed) + { + Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().UseOpacity(0); + if (Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].IsActive()) + Filters.Scene.Deactivate("CalamityMod:BrainOfCthulhuForcefield"); + } + else + { + if (!Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].IsActive()) + Filters.Scene.Activate("CalamityMod:BrainOfCthulhuForcefield"); + + NPC target = Main.npc[NPC.crimsonBoss]; + Vector2 targetPos = target.Center; + float shieldOpacity = target.AIOverride().ShieldOpacity; + float shieldScale = target.AIOverride().ShieldScale; + targetPos = Vector2.Transform(targetPos - Main.screenPosition, Main.GameViewMatrix.ZoomMatrix) / Main.ScreenSize.ToVector2(); + + Texture2D voronoi = ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/VoronoiShapes3").Value; + Texture2D depthNoise = ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Veins").Value; + + Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().Shader.Parameters["voronoi"].SetValue(voronoi); + Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().Shader.Parameters["depthNoise"].SetValue(depthNoise); + Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().Shader.Parameters["uScreenResolution"].SetValue(new Vector2(Main.graphics.GraphicsDevice.Viewport.Width, Main.graphics.GraphicsDevice.Viewport.Height)); + Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().UseProgress(0.15f * shieldScale); + Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().UseOpacity(shieldOpacity); + Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().UseColor(Color.Red); + Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().UseSecondaryColor(new Color(255, 0, 90)); //Crimson color (R:220,G:20,B:60,A:255). // Magenta color (R:255,G:0,B:255,A:255). + Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().UseDirection(targetPos); + } + + if (ScreenBlurStrength == 0f) + { + Filters.Scene["CalamityMod:RadialBlurShader"].GetShader().UseIntensity(0); + if (Filters.Scene["CalamityMod:RadialBlurShader"].IsActive()) + Filters.Scene.Deactivate("CalamityMod:RadialBlurShader"); + return; + } + + if (NPC.crimsonBoss == -1) + { + ScreenBlurStrength = Filters.Scene["CalamityMod:RadialBlurShader"].GetShader().Intensity * 0.9f; + Filters.Scene["CalamityMod:RadialBlurShader"].GetShader().UseIntensity(ScreenBlurStrength); + if (ScreenBlurStrength < 0.01f) + ScreenBlurStrength = 0f; + return; + } + + if (Filters.Scene["CalamityMod:RadialBlurShader"].IsLoaded) + { + if (!Filters.Scene["CalamityMod:RadialBlurShader"].IsActive()) + Filters.Scene.Activate("CalamityMod:RadialBlurShader"); + NPC boss = Main.npc[NPC.crimsonBoss]; + float counter = boss.ai[1] - boss.ai[2] - 240; + float distSQ = Main.LocalPlayer.DistanceSQ(boss.Center); + float distanceScaleFactor = 1; + if (distSQ > 592900) //770^2 + distanceScaleFactor = 1 / (1 + (((float)Math.Sqrt(distSQ) - 770) / 32f)); + + Filters.Scene["CalamityMod:RadialBlurShader"].GetShader().UseIntensity((ScreenBlurStrength + (((float)Math.Cos(counter * MathHelper.TwoPi / 15f) / 2f + 0.5f) * (0.4f * ScreenBlurStrength))) * distanceScaleFactor); + Filters.Scene["CalamityMod:RadialBlurShader"].GetShader().Shader.Parameters["uSaturation"].SetValue(20); + + Vector2 targetPos = Vector2.Transform(boss.Center - Main.screenPosition, Main.GameViewMatrix.ZoomMatrix) / Main.ScreenSize.ToVector2(); + + Filters.Scene["CalamityMod:RadialBlurShader"].GetShader().UseDirection(targetPos); + + } + } + } + + public override void PostUpdateEverything() + { + if (Main.curMusic != MusicID.Boss3 && Main.curMusic != MusicID.OtherworldlyBoss1) + previousMusic = Main.curMusic; + + if (previousMusic == -1) + previousMusic = MusicID.Crimson; + + } +} + diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs new file mode 100644 index 0000000000..f3b605ad05 --- /dev/null +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs @@ -0,0 +1,737 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.DataStructures; +using CalamityMod.Events; +using CalamityMod.Particles; +using CalamityMod.World; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.Audio; +using Terraria.ID; +using Terraria.ModLoader; +using Terraria.ModLoader.IO; +using static CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses.BrainOfCthulhu.BrainOfCthulhuAI; +using static CalamityMod.NPCs.VanillaNPCAIOverrides.RegularEnemies.RevengeanceAndDeathAI; + +namespace CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses.BrainOfCthulhu; + +public class CreeperAI : VanillaAIOverride +{ + internal float FlowTime = 0; + internal float FlowAmount => MathHelper.Lerp(0.1f, 0.15f, NPC.localAI[3]); + + internal enum CreeperAIState + { + Idle, + Charge + } + + internal int CreeperID { get => (int)NPC.ai[0]; set => NPC.ai[0] = value; } + internal CreeperAIState AIState { get => (CreeperAIState)NPC.ai[1]; set => NPC.ai[1] = (float)value; } + internal int Time = -1; + internal ref float AttackAngle => ref NPC.ai[2]; + internal ref float CachedValue1 => ref NPC.ai[3]; + internal int CachedValue2 = 0; + internal int PartnerIndex = -1; + internal Vector2 AttackPosition = Vector2.Zero; + internal float ConnectionOpacity = 0f; + + NPC brain => Main.npc[NPC.crimsonBoss]; + BrainOfCthulhuAI bocAI => brain.AIOverride(); + + float bossCounter => bocAI.Time; + + internal bool evenID => CreeperID % 2 == 0; + + int creeperCount + { + get + { + int c = NPC.CountNPCS(NPC.type); + if (c > GetBrainOfCthuluCreepersCountRevDeath()) + c = GetBrainOfCthuluCreepersCountRevDeath(); + return c; + } + } + + int localCreeperID => Main.npc.Where(n => n.active && n.type == NPCID.Creeper).ToList().IndexOf(NPC); + + float CreeperAmountRatio => creeperCount / (float)GetBrainOfCthuluCreepersCountRevDeath(); + + bool useBossAIState = true; + + public override bool EnableMultiplayerSmoothingAheadOfAI => true; + + public override void SetDefaults(Mod mod) + { + NPC.damage = NPC.defDamage = 36; // 64 (1.8x expert scaling) + } + + public override bool AI(Mod mod) + { + #region Despawn + if (NPC.crimsonBoss < 0) + { + NPC.active = false; + NPC.netUpdate = true; + return false; + } + #endregion + + #region Targetting + if (NPC.target < 0 || NPC.target == Main.maxPlayers || Main.player[NPC.target].dead || !Main.player[NPC.target].active) + CalamityUtils.CalamityTargeting(NPC, default); + #endregion + + if (bocAI.AIState < 0) + NPC.damage = 0; + + List bossAIStatesToUse = [ + BrainAIState.UndergroundSpawnAnimation, + BrainAIState.SurfaceSpawnAnimation, + BrainAIState.Stunned, + BrainAIState.CreeperSwipes, + BrainAIState.CreeperSwings, + BrainAIState.CreeperOrbit, + BrainAIState.CreeperSpiral, + BrainAIState.TelekineticOnslaught + ]; + useBossAIState = bossAIStatesToUse.Contains(bocAI.AIState) && bossCounter >= 0; + + if (bocAI.AIState == BrainAIState.UndergroundSpawnAnimation || bocAI.AIState == BrainAIState.SurfaceSpawnAnimation) + NPC.dontTakeDamage = true; + else + NPC.dontTakeDamage = false; + + if (useBossAIState) + switch (bocAI.AIState) + { + case BrainAIState.UndergroundSpawnAnimation: + case BrainAIState.SurfaceSpawnAnimation: + SpawnAnimation(); + break; + case BrainAIState.TelekineticOnslaught: + TelekineticOnslaught(); + break; + case BrainAIState.Stunned: + //Only used for when the Creepers are spawned just as the stun is ending. + NPC.velocity *= 0.9f; + NPC.damage = 0; + break; + case BrainAIState.CreeperSwipes: + CreeperSwipes(); + break; + case BrainAIState.CreeperSwings: + CreeperSwings(); + break; + case BrainAIState.CreeperOrbit: + CreeperOrbit(); + break; + case BrainAIState.CreeperSpiral: + CreeperSpiral(); + break; + } + + else + switch (AIState) + { + case CreeperAIState.Idle: + CreeperIdle(); + break; + case CreeperAIState.Charge: + CreeperCharge(); + break; + } + + FlowTime += 0.01f * (2 * (1 + ConnectionOpacity)); + + return false; + } + + #region Attacks + Animations + + private void SpawnAnimation() + { + float baseRotation = MathHelper.TwoPi / (GetBrainOfCthuluCreepersCountRevDeath() / 2f) * (CreeperID / 2f); + Vector2 goalLocation; + float speedCap = 8f; + float accel = 1f; + float acceptableDist = 9216; + Player player = Main.player[NPC.target]; + + if (bocAI.SpawnTime != 0 && Time >= 0) //Brain has appeared + { + float brainTime = bossCounter - Math.Abs(bocAI.SpawnTime); + + if (brainTime < 180) + { + Vector2 baseOffset = new Vector2(evenID ? -360 : 360, 0); + Vector2 rotationOffset = Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 120f * (evenID ? -1 : 1))) * 128; + goalLocation = player.Center + baseOffset + rotationOffset; + } + else if (brainTime < 240) + { + Vector2 baseOffset = new Vector2(evenID ? -200 : 200, 64); + Vector2 rotationOffset = Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 60f * (evenID ? -1 : 1))) * 32; + goalLocation = brain.Center + baseOffset + rotationOffset; + speedCap = 12; + accel = 2f; + acceptableDist = 4096; + } + else + { + Vector2 baseOffset = new Vector2(evenID ? -360 : 360, -64); + Vector2 rotationOffset = Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 60f * (evenID ? -1 : 1))) * 128; + goalLocation = brain.Center + baseOffset + rotationOffset; + speedCap = 12; + accel = 2f; + acceptableDist = 4096; + } + Time++; + } + else + { + if (Time >= 0) //Has been brought down + { + Vector2 baseOffset = new Vector2(evenID ? -360 : 360, 0); + Vector2 rotationOffset = Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 120f * (evenID ? -1 : 1))) * 128; + goalLocation = player.Center + baseOffset + rotationOffset; + Time++; + } + else //Hasnt been brought down + { + Vector2 baseOffset = new Vector2(evenID ? -256 : 256, 0); + Vector2 rotationOffset = Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 120f * (evenID ? -1 : 1))) * 64; + goalLocation = brain.Center + baseOffset + rotationOffset; + } + } + + if (NPC.DistanceSQ(goalLocation) > acceptableDist) + { + NPC.velocity += NPC.DirectionTo(goalLocation) * accel; + NPC.velocity = NPC.velocity.ClampMagnitude(0f, speedCap); + } + } + + private void TelekineticOnslaught() + { + if (Time > 0) + { + Point tileCoords = AttackPosition.ToTileCoordinates(); + if (WorldGen.SolidOrSlopedTile(tileCoords.X, tileCoords.Y)) + { + float rayDist = CalamityUtils.PreciseDistanceToTileCollisionHit(brain.Center, AttackAngle, 800, 4); + AttackPosition = brain.Center + (AttackAngle.ToRotationVector2() * (rayDist - 64)); + } + + if (NPC.DistanceSQ(AttackPosition) > 4096) + { + NPC.velocity += NPC.DirectionTo(AttackPosition); + NPC.velocity = NPC.velocity.ClampMagnitude(0f, 10f); + } + else + NPC.velocity *= 0.8f; + ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f); + NPC.damage = 0; + } + else + useBossAIState = false; + + Time++; + } + + private void CreeperSwipes() + { + Vector2 goalLocation; + if (bossCounter < 15) + { + useBossAIState = false; + Time = -1; + AIState = CreeperAIState.Idle; + } + + if (brain.AIOverride().AttackList.Contains((byte)NPC.whoAmI)) + { + if (Time < 0) + Time = 0; + } + else + { + if (Time >= 0) + Time = -1; + } + + float baseRotation = MathHelper.TwoPi / (GetBrainOfCthuluCreepersCountRevDeath() / 2f) * (CreeperID / 2f); + bool singleHand = bocAI.AttackFlag; + int handSide = bocAI.AttackSign; + + if (Time == -1) + { + NPC.damage = 0; + NPC.knockBackResist = 0.72f; + + ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0f); + + if (!singleHand) + goalLocation = brain.Center + (Vector2.UnitY * -32f) + (Vector2.UnitX * (evenID ? -256 : 256)) + (Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 30f * (evenID ? -1 : 1))) * new Vector2(32, 96)); + else + goalLocation = brain.Center + (Vector2.UnitY * -32f) + (Vector2.UnitX * 256 * handSide) + (Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 30f * handSide)) * new Vector2(32, 96)); + + goalLocation += Main.player[brain.target].velocity * 24f; + float distToGoal = NPC.Center.Distance(goalLocation); + NPC.velocity = NPC.DirectionTo(goalLocation) * (2f + MathHelper.Clamp(distToGoal / 24f, 0f, 64f)); + } + else + { + if (Time == 0) + NPC.netUpdate = true; + + NPC.damage = NPC.defDamage; + NPC.knockBackResist = 0f; + + ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f); + + float accel = 2f; + float speed = 12f; + + if (Time < brain.AIOverride().SwipeDelay) + { + if (!singleHand) + goalLocation = brain.Center + (Vector2.UnitY * -96f) + (Vector2.UnitX * (evenID ? -300 : 300)) + (Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 30f * (evenID ? -1 : 1))) * new Vector2(32, 96)); + else + goalLocation = brain.Center + (Vector2.UnitY * -96f) + (Vector2.UnitX * 300 * handSide) + (Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 30f * handSide)) * new Vector2(32, 96)); + + goalLocation += Main.player[brain.target].velocity * 24f; + NPC.velocity += NPC.DirectionTo(goalLocation) * accel; + NPC.velocity = NPC.velocity.ClampMagnitude(0f, speed); + } + else + { + if (!singleHand) + goalLocation = brain.Center + (Vector2.UnitY * -96f) + (Vector2.UnitX * (evenID ? -256 : 256)) + (Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 30f * (evenID ? -1 : 1))) * new Vector2(32, 96)); + else + goalLocation = brain.Center + (Vector2.UnitY * -96f) + (Vector2.UnitX * 256 * handSide) + (Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 30f * handSide)) * new Vector2(32, 96)); + + goalLocation.Y += MathHelper.Lerp(0, 420, CalamityUtils.SineInOutEasing(MathHelper.Clamp((Time - brain.AIOverride().SwipeDelay) / 20f, 0f, 1f), 1)); + + if (!singleHand) + goalLocation.X += MathHelper.Lerp(0f, 900f, CalamityUtils.SineInOutEasing(MathHelper.Clamp((Time - (brain.AIOverride().SwipeDelay + 5)) / 55f, 0f, 1f), 1)) * (evenID ? 1 : -1); + else + 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++; + } + } + + private void CreeperSwings() + { + if (brain.AIOverride().AttackList.Contains((byte)NPC.whoAmI)) + { + if (Time < 0) + { + Time = 0; + NPC.netUpdate = true; + AttackPosition = NPC.Center; + } + } + else + { + if (Time >= 0) + Time = -1; + } + + if (Time < 0) + { + float baseRotation = (brain.Center - Main.player[brain.target].Center).ToRotation(); + bool evenID = CreeperID % 2 == 0; + Vector2 goalLocation = brain.Center + Vector2.UnitX.RotatedBy(baseRotation + Math.Sin(bossCounter / 60f + CreeperID) * (evenID ? -1 : 1)) * (evenID ? 175 : 250); + if (NPC.DistanceSQ(goalLocation) > 9216) + { + NPC.velocity += NPC.DirectionTo(goalLocation); + NPC.velocity = NPC.velocity.ClampMagnitude(0f, 8f); + } + ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0f); + } + else + { + Player sharedTarget = Main.player[brain.target]; + Vector2 dashDir = AttackAngle.ToRotationVector2(); + if (!bocAI.OnSecondCreeperPhase) // Swipe Attack + { + float positioningTime = LightSwipeTravelTime + LightSwipeAttackDelay; + + if (Time <= positioningTime) + { + 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 + { + AttackPosition = Vector2.Zero; + NPC.damage = NPC.defDamage; + NPC.knockBackResist = 0f; + int reelbackTime = 22; + + if (Time < (positioningTime + reelbackTime)) + { + float reelBackSpeedExponent = 2.6f; + float reelBackCompletion = Utils.GetLerpValue(0f, reelbackTime, Time - positioningTime, true); + float reelBackSpeed = MathHelper.Lerp(2.5f, 16f, MathF.Pow(reelBackCompletion, reelBackSpeedExponent)); + Vector2 reelBackVelocity = dashDir * -reelBackSpeed; + NPC.velocity = Vector2.Lerp(NPC.velocity, reelBackVelocity, 0.25f); + + if (Time == positioningTime + reelbackTime - 5) + SoundEngine.PlaySound(SoundID.DD2_MonkStaffSwing, NPC.Center); + } + else if (Time == (positioningTime + reelbackTime)) + NPC.velocity = dashDir * 32; + else + { + NPC.velocity *= 0.9f; + if (Time >= positioningTime + reelbackTime + 15) + { + NPC.damage = 0; + Time = -1; + brain.AIOverride().AttackList.Remove((byte)NPC.whoAmI); + AttackPosition = Vector2.Zero; + ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0f); + return; + } + } + } + } + else //Crush Attack + { + float positioningTime = StrongSwipeTravelTime + StrongSwipeAttackDelay; + + if (Time <= positioningTime) + { + if (AttackPosition == Vector2.Zero) + AttackPosition = NPC.Center; + 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 + { + NPC.damage = NPC.defDamage; + NPC.knockBackResist = 0f; + int reelbackTime = 18; + float swingTime = 10f; + + if (Time <= (positioningTime + reelbackTime)) + { + float reelBackSpeedExponent = 2.6f; + float reelBackCompletion = Utils.GetLerpValue(0f, reelbackTime, Time - positioningTime, true); + float reelBackSpeed = MathHelper.Lerp(2.5f, 16f, MathF.Pow(reelBackCompletion, reelBackSpeedExponent)); + Vector2 reelBackVelocity = dashDir * -reelBackSpeed; + NPC.velocity = Vector2.Lerp(NPC.velocity, reelBackVelocity, 0.25f); + + if (Time == positioningTime + reelbackTime - 5) + SoundEngine.PlaySound(SoundID.DD2_MonkStaffSwing, NPC.Center); + + if (Time == (positioningTime + reelbackTime)) + AttackPosition = NPC.Center; + } + else if (Time <= (positioningTime + reelbackTime + swingTime)) + { + if (Main.npc[PartnerIndex].active) + { + 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); + SoundEngine.PlaySound(NPC.HitSound, NPC.Center); + NPC.velocity = dashDir * -8; + Vector2 attackCenter = AttackPosition + dashDir * 200; + if (dashDir.X <= 0) + { + //WaterFoam (0.25 -> 1), SoftRoundExplosion (0.025 -> 0.1), SmokeExplosion(0.05 -> 0.15) + CustomPulse splatter = new(attackCenter, Vector2.Zero, Color.Red, "CalamityMod/Particles/SmokeExplosion", Vector2.One, Main.rand.NextFloatDirection(), 0.05f, 0.15f, 24); + GeneralParticleHandler.SpawnParticle(splatter); + } + + if (Main.netMode != NetmodeID.MultiplayerClient) + for (int i = -1; i <= 1; i++) + Projectile.NewProjectile(NPC.GetSource_FromThis(), attackCenter, dashDir.RotatedBy(MathHelper.PiOver2 + (MathHelper.Pi / 6f * i)) * 8f, ProjectileID.BloodShot, BloodShotDamage, 0.5f); + } + } + else + NPC.velocity = dashDir * 19.6f; + } + else if (Time < (positioningTime + reelbackTime + swingTime + 30)) + { + NPC.velocity *= 0.96f; + } + else + { + NPC.damage = 0; + Time = -1; + brain.AIOverride().AttackList.Remove((byte)NPC.whoAmI); + AttackPosition = Vector2.Zero; + ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0.5f); + return; + } + } + } + + ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f); + Time++; + } + } + + private void CreeperOrbit() + { + if (bossCounter == 0) + { + 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((byte)NPC.whoAmI)) + { + if (Time < 0) + { + Time = 0; + NPC.netUpdate = true; + } + } + else + { + if (Time >= 0) + Time = -1; + } + + if (Time >= 0) + { + float telegraphPeriod = OrbitAttackInterval * 0.25f; + float shiftPeriod = (OrbitAttackInterval - telegraphPeriod) / 2f; + if (Time < telegraphPeriod) + dist = MathHelper.Lerp(dist, OrbitTelegraphRadius, CalamityUtils.SineOutEasing(Time / telegraphPeriod, 1)); + else if (Time < shiftPeriod + telegraphPeriod) + dist = MathHelper.Lerp(OrbitTelegraphRadius, 16, CalamityUtils.SineInOutEasing((Time - telegraphPeriod) / shiftPeriod, 1)); + else + { + dist = MathHelper.Lerp(16, dist, CalamityUtils.SineInOutEasing((Time - telegraphPeriod - shiftPeriod) / shiftPeriod, 1)); + if (Time > OrbitAttackInterval) + { + Time = -2; + brain.AIOverride().AttackList.Remove((byte)NPC.whoAmI); + } + } + ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f, 0.1f); + Time++; + } + else + ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0f, 0.05f); + + 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; + + if (bossCounter < OrbitSetupDuration) + { + NPC.damage = 0; + + if (bossCounter == 0) + AttackPosition = NPC.Center; + NPC.Center = Vector2.Lerp(AttackPosition, bocAI.AttackPosition + rotation, CalamityUtils.SineOutEasing(bossCounter / OrbitSetupDuration, 1)); + DisableMultiplayerSmoothing = true; + } + else + { + NPC.damage = NPC.defDamage; + NPC.Center = bocAI.AttackPosition + rotation; + DisableMultiplayerSmoothing = true; + } + } + + private void CreeperSpiral() + { + int tendrilID = (CreeperID % TendrilCount) + 1; + + if (bossCounter == 0) + { + 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; + int groupCount = CachedValue2; + float placementRatio = (index + 1) / (float)(groupCount + 1); + + float spiralAngle = bocAI.AttackRotation; + float goalAngle = spiralAngle + ((MathHelper.TwoPi / TendrilCount) * tendrilID); + + float angularVelocity = (goalAngle - AttackAngle) / (16f + (placementRatio * 16f)); + + AttackAngle += angularVelocity; + + float goalRadius = TendrilStartDistance + (TendrilLength * placementRatio); + goalRadius += (float)Math.Sin(bossCounter / 20f) * MathHelper.Lerp(MaxCreeperSway, 0, groupCount / (float)(GetBrainOfCthuluCreepersCountRevDeath() / 3)) * (index % 2 == 0 ? -1 : 1); + + Vector2 position = brain.Center + (AttackAngle.ToRotationVector2() * goalRadius); + if (bossCounter >= SpiralSetupTime) + { + NPC.Center = position; + DisableMultiplayerSmoothing = true; + + NPC.damage = NPC.defDamage; + NPC.knockBackResist = 0f; + + ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f); + } + else if (bossCounter < SpiralSetupTime / 10f) + NPC.velocity *= 0.66f; + else + { + 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; + } + } + + private void CreeperIdle() + { + if (Time == 0) //Ordinarily would be set by Brain. This currently doesn't happen. + { + AIState = CreeperAIState.Charge; + return; + } + + NPC.knockBackResist = 0.72f; + NPC.damage = 0; + + float baseRotation = MathHelper.TwoPi / (GetBrainOfCthuluCreepersCountRevDeath() / 2f) * (CreeperID / 2f); + Vector2 goalLocation = brain.Center + (Vector2.UnitX * (evenID ? -256 : 256)) + Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 60f * (evenID ? -1 : 1))) * 64; + if (NPC.DistanceSQ(goalLocation) > 9216) + { + NPC.velocity += NPC.DirectionTo(goalLocation); + NPC.velocity = NPC.velocity.ClampMagnitude(0f, 8f); + } + ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0f); + Time = -1; + AttackPosition = Vector2.Zero; + } + + //Unused + private void CreeperCharge() + { + Player target = Main.player[NPC.target]; + + if (Time < CreeperChargePositioningTime) + { + Vector2 goalLocation = target.Center + ((NPC.Center - target.Center).SafeNormalize(-Vector2.UnitY).RotatedBy((evenID ? -MathHelper.PiOver4 : MathHelper.PiOver4)) * 96); + if (NPC.DistanceSQ(goalLocation) > 4096) + { + NPC.velocity += NPC.DirectionTo(goalLocation); + NPC.velocity = NPC.velocity.ClampMagnitude(0f, 12f); + } + ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f); + } + else + { + NPC.damage = NPC.defDamage; + NPC.knockBackResist = 0f; + + if (Time < (CreeperChargePositioningTime + CreeperChargeWindUpTime)) + { + float reelBackSpeedExponent = 2.6f; + float reelBackCompletion = Utils.GetLerpValue(0f, CreeperChargeWindUpTime, Time - CreeperChargePositioningTime, true); + float reelBackSpeed = MathHelper.Lerp(2.5f, 16f, MathF.Pow(reelBackCompletion, reelBackSpeedExponent)); + Vector2 reelBackVelocity = NPC.DirectionTo(Main.player[brain.target].Center) * -reelBackSpeed; + NPC.velocity = Vector2.Lerp(NPC.velocity, reelBackVelocity, 0.25f); + + if (Time == CreeperChargePositioningTime + CreeperChargeWindUpTime - 5) + SoundEngine.PlaySound(SoundID.DD2_MonkStaffSwing, NPC.Center); + } + else if (Time == CreeperChargePositioningTime + CreeperChargeWindUpTime) + NPC.velocity = NPC.DirectionTo(Main.player[brain.target].Center) * 24; + else + { + NPC.velocity *= 0.975f; + if (Time >= CreeperChargePositioningTime + CreeperChargeWindUpTime + 30) + { + NPC.damage = 0; + Time = -10; + AIState = CreeperAIState.Idle; + return; + } + } + } + Time++; + } + + #endregion + + public override void SendExtraAI(BitWriter bitWriter, BinaryWriter binaryWriter) + { + binaryWriter.Write(Time); + binaryWriter.Write(CachedValue2); + binaryWriter.Write(PartnerIndex); + + binaryWriter.WritePackedWorldPosition(AttackPosition); + } + + public override void ReceiveExtraAI(BitReader bitReader, BinaryReader binaryReader) + { + Time = binaryReader.ReadInt32(); + CachedValue2 = binaryReader.ReadInt32(); + PartnerIndex = binaryReader.ReadInt32(); + + AttackPosition = binaryReader.ReadPackedWorldPosition(); + } + + public override void HitEffect(Mod mod, NPC.HitInfo hit) + { + if (NPC.life <= 0) + { + List verletTendril = BrainOfCthulhuSystem.VerletTendrils[NPC.AIOverride().CreeperID]; + if (verletTendril is null) + return; + + for (int i = 0; i < verletTendril.Count; i++) + { + Vector2 start = verletTendril[i].position; + Vector2 end = i == verletTendril.Count - 1 ? NPC.Center : verletTendril[i + 1].position; + + float rotation = (end - start).ToRotation(); + + float dist = Vector2.Distance(start, end); + Vector2 scale = new(1f, dist / BrainOfCthulhuSystem.tendril.Height()); + + BrokenTendril gore = new(start, Vector2.UnitY.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver4, MathHelper.PiOver4)) * -Main.rand.NextFloat(2f, 4f), rotation, scale, 60); + GeneralParticleHandler.SpawnParticle(gore); + + } + + BrainOfCthulhuSystem.VerletTendrils[NPC.AIOverride().CreeperID] = []; + } + } + + public override bool PreDraw(Mod mod, SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) => false; +} + diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/FalseBrain.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/FalseBrain.cs new file mode 100644 index 0000000000..5e7beed8f4 --- /dev/null +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/FalseBrain.cs @@ -0,0 +1,188 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Particles; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.Audio; +using Terraria.GameContent; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses.BrainOfCthulhu; + +[AutoloadBossHead] +public class FalseBrain : ModNPC, ILocalizedModType +{ + public new string LocalizationCategory => "NPCs"; + public override string BossHeadTexture => "Terraria/Images/NPC_Head_Boss_23"; + + public override void SetStaticDefaults() + { + this.HideFromBestiary(); + Main.npcFrameCount[Type] = 4; + } + + public override void SetDefaults() + { + NPC.width = 160; + NPC.height = 110; + NPC.damage = 0; + NPC.lifeMax = 1; + NPC.knockBackResist = 0f; + NPC.noGravity = true; + NPC.noTileCollide = true; + NPC.boss = true; + NPC.immortal = true; + NPC.dontTakeDamage = true; + NPC.chaseable = false; + NPC.npcSlots = 0f; + NPC.netAlways = true; + NPC.ShowNameOnHover = false; + Music = MusicID.Boss3; + + NPC.localAI[0] = Main.rand.Next(5); + NPC.localAI[1] = 1 + Main.rand.NextFloat(-0.5f, 0.5f); + } + private int Variant => (int)NPC.localAI[0]; + private float Angle => NPC.ai[0]; + private ref float Time => ref NPC.ai[1]; + internal bool BeenHit = false; + int AttackTime = 0; + int SpawnTime = 60; + + internal static float TimeDivisor => 360f; + internal float DrawPriority => (float)Math.Cos(-Time * MathHelper.TwoPi / TimeDivisor); + internal static List blackListedProjectiles = []; + + public override void AI() + { + if (NPC.crimsonBoss == -1) + { + NPC.active = false; + return; + } + + 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; + + if (AttackTime == 60) + NPC.active = false; + + AttackTime++; + } + else + { + float lerp = CalamityUtils.SineInOutEasing(MathHelper.Clamp(SpawnTime / -30f, 0f, 1f), 1); + float baseDist = 240; + float circleDist = 480; + if (SpawnTime != -30) + { + baseDist = MathHelper.Lerp(480, 240, lerp); + circleDist = MathHelper.Lerp(240, 480, lerp); + } + NPC.Center = brain.AIOverride().AttackPosition + Vector2.UnitX.RotatedBy(Angle) * (baseDist + (circleDist * ((float)Math.Sin(-Time * MathHelper.TwoPi / TimeDivisor) / 2f + 0.5f))); + NPC.Center += Vector2.UnitX.RotatedBy(Angle + MathHelper.PiOver2) * (90 * (float)Math.Cos(Time * MathHelper.TwoPi / TimeDivisor)); + } + + if (SpawnTime > 0) + { + if (--SpawnTime == 0) + NPC.dontTakeDamage = false; + } + else if (SpawnTime > -30) + Time += --SpawnTime / -30f; + else + Time++; + } + + public override void OnHitByItem(Player player, Item item, NPC.HitInfo hit, int damageDone) + { + SmiteFool(player); + } + + public override void OnHitByProjectile(Projectile projectile, NPC.HitInfo hit, int damageDone) + { + if (!projectile.Calamity().IgnoreBoCIllusions && projectile.owner != -1) + SmiteFool(Main.player[projectile.owner]); + } + + private void SmiteFool(Player fool) + { + if (!BeenHit) + { + for (int i = 0; i < 6; i++) + { + Vector2 dir = fool.Center - NPC.Center; + int lifeTime = 24; + dir /= lifeTime / 2f * 5f; + dir *= i; + DirectionalPulseRing pulse = new(NPC.Center, dir, i % 2 == 0 ? Color.Red : Color.Orange, new Vector2(0.5f, 1), dir.ToRotation(), 0f, i / 5f, lifeTime + 8); + GeneralParticleHandler.SpawnParticle(pulse); + } + + BeenHit = true; + SoundEngine.PlaySound(SoundID.Zombie105, NPC.Center); //LC Laugh + fool.AddBuff(BuffID.Darkness, 900); + fool.AddBuff(BuffID.Bleeding, 900); + fool.AddBuff(BuffID.Confused, 60); + int timeToAdd = 600; + int bbIndex = fool.buffType.ToList().IndexOf(ModContent.BuffType()); + if (bbIndex != -1) + { + timeToAdd /= 2; + timeToAdd += fool.buffTime[bbIndex]; + } + fool.AddBuff(ModContent.BuffType(), timeToAdd); + + fool.Calamity().adrenaline = 0; + + NPC.dontTakeDamage = true; + } + } + + public override void FindFrame(int frameHeight) + { + NPC.frameCounter += 0.2f * NPC.localAI[1]; + if ((int)NPC.frameCounter > 3) + NPC.frameCounter = 0; + } + + internal void DrawSelf(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) + { + Texture2D tex = TextureAssets.Npc[Type].Value; + + Rectangle frame = tex.Frame(5, 4, Variant, (int)NPC.frameCounter); + + Vector2 scaleDistort = new Vector2((float)Math.Cos(Main.GlobalTimeWrappedHourly * MathHelper.TwoPi * 2) / 2f, (float)Math.Sin(Main.GlobalTimeWrappedHourly * MathHelper.TwoPi * 2) / 2f); + + float endLerp = AttackTime / 60f; + float startLerp = SpawnTime / 60f; + + if (SpawnTime > 0) + { + drawColor *= (1 - startLerp); + scaleDistort *= startLerp; + } + else + { + drawColor = Color.Lerp(drawColor, Color.Red, endLerp) * (1 - endLerp); + scaleDistort *= endLerp; + } + + spriteBatch.Draw(tex, NPC.Center + (Vector2.UnitY * 16) - screenPos, frame, drawColor, NPC.rotation, frame.Size() * 0.5f, (Vector2.One + scaleDistort) * NPC.scale, 0, 0); + } + + public override bool PreDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) => false; +} diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/FalseBrain.png b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/FalseBrain.png similarity index 100% rename from NPCs/VanillaNPCAIOverrides/Bosses/FalseBrain.png rename to NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/FalseBrain.png diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhuAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhuAI.cs deleted file mode 100644 index 9a17085899..0000000000 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhuAI.cs +++ /dev/null @@ -1,5082 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using CalamityMod.Buffs.DamageOverTime; -using CalamityMod.DataStructures; -using CalamityMod.Events; -using CalamityMod.Particles; -using CalamityMod.Utilities.Daybreak; -using CalamityMod.World; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using ReLogic.Content; -using Terraria; -using Terraria.Audio; -using Terraria.Chat; -using Terraria.DataStructures; -using Terraria.GameContent; -using Terraria.Graphics.Effects; -using Terraria.Graphics.Shaders; -using Terraria.ID; -using Terraria.Localization; -using Terraria.ModLoader; -using Terraria.ModLoader.IO; - -namespace CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses -{ - public class BrainOfCthulhuAI : VanillaAIOverride - { - private static SoundStyle StunnedHit = new("CalamityMod/NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Stun_Hit", 3); - private static SoundStyle ShieldDown = new("CalamityMod/NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Shield_Down"); - private static SoundStyle ShieldUp = new("CalamityMod/NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Shield_Up"); - private static SoundStyle IntroRoar = new("CalamityMod/NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Roar"); - private static SoundStyle Roar = new("CalamityMod/NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Short_Roar"); - - public static bool SummonedViaItem = false; - internal List BoCAfterImages = []; - internal float ShieldOpacity = 1f; - internal float ShieldScale = 1f; - private Vector2 BoCDrawOffset = Vector2.Zero; - private Rectangle BoCFrame = new(0, 0, 198, 180); - - #region Balancing Values - - #region Projectile Damage Values - internal static int BloodShotDamage => 12; // 48 - internal static int BloodScytheDamage => 12; // 48 - internal static int IchorShotDamage => 12; // 48 - internal static int CrimsonEyeDamage => 12; // 48 - #endregion - - internal static float Phase1DefenseMultiplier => 1.5f; //Multiplies BoC's default defense value by this amount when in Phase 1. - - #region Health Gates - internal static float DesperateOnslaughtCreeperHealthGate => 0.1f; //When the cumulative health % of all creepers falls below this value, BoC will begin its pre-stun attack upon entering its idle phase. - internal static float Phase2HealthGate => 0.5f; //When BoC's health % falls below this value, it will begin entering Phase 2 - #endregion - - internal static float DespawnRange => 6000f; - - #region Phase 1 Attack Values - - #region Idle Period - internal static int IdlePeriodDuration => 180; - internal static int CreeperChargeDelayMin => 70; - internal static int CreeperChargeDelayMax => 100; - internal static int CreeperChargePositioningTime => 60; - internal static int CreeperChargeWindUpTime => 22; - #endregion - - internal static int StunDuration => 480; - - #region Creeper Swipes - internal static int SwipesStartupDuration => 120; - internal int SwipeDuration => 60 + SwipeDelay; - internal int SwipeDelay => AttackFlag ? 30 : CalamityWorld.death ? 30 : 45; - internal static int SwipeAmount => 4; - internal int SwipeIchorDelay => 30 + SwipeDelay; - #endregion - - #region Creeper Crush - internal static int LightSwipeDelay => 60; - internal static int LightSwipeAmount => CalamityWorld.death ? 8 : 6; - internal static int LightSwipeTravelTime => 30; - internal static int LightSwipeAttackDelay => 10; - internal static int LightSwipeDuration => CalamityWorld.death ? 45 : 60; - internal static int StrongSwipeDelay => 90; - internal static int StrongSwipeAmount => CalamityWorld.death ? 7 : 5; - internal static int StrongSwipeTravelTime => 45; - internal static int StrongSwipeAttackDelay => 15; - internal static int StrongSwipeDuration => CalamityWorld.death ? 60 : 80; - #endregion - - #region Creeper Orbit - internal static int OrbitSetupDuration => 60; - internal static int OrbitDuration => 720; - internal static int OrbitAttackInterval => 120; - internal static int OrbitAttackParticipantCount => CalamityWorld.death ? 4 : 3; - internal static float OrbitStandardRadius => 320f; - internal static float OrbitTelegraphRadius => 480f; - internal static float BaseRotationSpeed => 0.0175f; - #endregion - - #region Creeper Spiral - internal static int SpiralDuration => 720; - internal static int SpiralSetupTime => 90; - internal static int TendrilCount => 3; - internal static float TendrilLength => 512; - internal static float TendrilStartDistance => 64; - internal static float MaxCreeperSway => 64; - internal static int StartingTimePerRevolutionMax => 270; - internal static int StartingTimePerRevolutionMin => 180; - internal static int EndingTimePerRevolutionMax => 210; - internal static int EndingTimePerRevolutionMin => 120; - internal static int SpeedUpDelayTime => 120; - internal static int SpeedUpExtensionTime => 120; - internal static float TurnAroundRatio => 0.6f; //In the second creeper phase, the creeper spiral will turn around at this completion percentage of the attack; - internal static float TurnAroundDurationRatio => 0.1f; //The amount of time that it'll take for the creeper spiral to turn around - - #endregion - - #endregion - - #region Phase 2 Attack Values - - internal static float DefaultTeleportDistance => 360f; - - #region Idle Period - internal static int ChaseTime => 160; - internal static int MaxChases => 3; - internal static int IdleTeleportDuration => CalamityWorld.death ? 36 : 44; - #endregion - - #region Bloodletting - internal static int BloodlettingDuration => 765; - internal static Vector2 HoverDistance => new (420f, 270f); - internal static float HoverEndHeight => 300f; - internal static int IchorRate => CalamityWorld.death ? 8 : 10; - internal static float IchorSpread => 1.5f; - internal static float IchorVelocity => 3f; - internal static int BloodshotRate => 90; - internal static float BloodshotVelocity => 10f; - internal static int DashPrepTime => 90; - internal static int DashReelbackTime => 20; - internal static int DashDuration => 30; - internal static float DashVelocity => 32f; - internal static int DashScytheRate => CalamityWorld.death ? 5 : 6; - #endregion - - #region Sanguine Scythes - internal static int SanguineTeleportCount => 5; - internal static int SanguineScytheCount => CalamityWorld.death ? 12 : 10; - internal static int SanguineTeleportDuration => 30; - internal static float SanguineTeleportDistance => 440f; - internal static Vector2 SanguineFinalTeleportOffset => new(720, 300); - internal static int SanguineAttackEndDelay => 30; - internal static int SanguineAttackEndDuration => 100; - internal static int SanguineAttackEndIchorRate => 10; - - #endregion - - #region Crimson Eyes - internal static int CrimsonEyeAttackIdleDuration => 210; - internal static int CrimsonEyeAttackSetUpDuration => 30; - internal static int CrimsonEyeAttackBuildUpDuration => 120; - - internal static int CrimsonEyeRate => 60; - internal static int CrimsonEyeCap => 40; - - internal static int CrimsonEyeAttackDuration => 960; - internal static int CrimsonEyeAttackEndDuration => 210; - internal static float TurnAccelerationMultiplier => 0.01f; //Base multiplier for the boss' course correction rotation - internal static float TurnAccelerationDistanceBuffer => 160f; //Determines the minimum distance it must be at before it can begin redirecting. - internal static float TurnAccelerationDistanceDivisor => 72f; //Determines how much the distance affects its turn amount. Larger number means it must get further from the player in order to correct its course - #endregion - - #region Illusion Dash - internal static float IllusionDashTeleportDistance => 300f; - internal static int IllusionDashTeleportDuration => 30; - internal static float IllusionDashCloseInDistance => 300f; - internal static float IllusionDashStartingSpinSpeed => 0.125f; - internal static int IllusionDashSpinDuration => 100; - internal static int IllusionDashFakeoutTeleportDuration => 16; - internal static float IllusionDashVelocity => 30f; - - #endregion - - #region Illusion Trick - internal static int IllusionTrickAngleGroups => CalamityWorld.death ? 8 : 6; - internal static int IllusionTrickGroupSize => CalamityWorld.death ? 5 : 4; - internal static int IllusionTrickStunDuration => 120; - internal static int IllusionTrickTimeLimit => 960; - - #endregion - - #endregion - - #endregion - - internal enum BrainAIState - { - //Spawn Animation - UndergroundSpawnAnimation = -2, - SurfaceSpawnAnimation, - //Phase 1 - Idle, - CreeperSwipes, - CreeperCrush, - CreeperOrbit, - CreeperSpiral, - DesperateOnslaught, - Stunned, - //Phase Transition - Phase2TransitionClosed, - Phase2TransitionOpen, - //Phase 2 - Phase2Idle, - CrimsonEyes, - SanguineScythes, - Bloodletting, - IllusionDash, - IllusionTrick, - //Defeat - DeathAnimation - } - - internal BrainAIState AIState { get => (BrainAIState)NPC.ai[0]; set => NPC.ai[0] = (float)value; } - internal BrainAIState PreviousAttack = BrainAIState.Idle; - internal ref float Time => ref NPC.ai[1]; - internal ref float DespawnTime => ref NPC.ai[2]; - internal ref float AnimationTime => ref NPC.ai[3]; - internal float TeleportTime = 0; - internal float TeleportDuration = 0; - internal float SpawnTime = 0; - internal int SpawnDelay = 0; - internal bool OnSecondCreeperPhase = false; - - internal float CachedRatio = 0f; - private bool isNegative = false; - internal int AttackSign { get => isNegative ? -1 : 1; set => isNegative = value == -1 ? true : false; } - internal float AttackRotation = 0; - internal float AttackTime = 0; - internal int AttackCounter = 0; - internal bool AttackFlag = false; - internal Vector2 AttackPosition = Vector2.Zero; - internal List availableAttacks = []; - internal List AttackList = []; - - public override void SetDefaults(Mod mod) - { - DisableMultiplayerSmoothing = true; - - BoCDrawOffset = Vector2.Zero; - ShieldOpacity = 1f; - ShieldScale = 1f; - RevBoCSystem.ScreenBlurStrength = 0f; - - if (!Main.dedServ) - { - int brainOfCthuluCreepersCount = GetBrainOfCthuluCreepersCountRevDeath(); - RevBoCSystem.VerletTendrils = new List[brainOfCthuluCreepersCount]; - - for (int i = 0; i < brainOfCthuluCreepersCount; i++) - { - List tendril = []; - for (int j = 0; j < 28; j++) - tendril.Add(new(NPC.Center)); - - RevBoCSystem.VerletTendrils[i] = tendril; - } - } - } - - 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 - CalamityTargetingParameters options = CalamityTargetingParameters.BossDefaults; - options.aggroRatio = -1f; - options.finishThemOff = true; - CalamityUtils.CalamityTargeting(NPC, options); - } - Player target = Main.player[NPC.target]; - bool onSurface = target.Center.Y / 16 < Main.worldSurface; - - NPC.Center = target.Center + Vector2.UnitY * (onSurface ? 900 : -900); - NPC.dontTakeDamage = true; - - AIState = onSurface ? BrainAIState.SurfaceSpawnAnimation : BrainAIState.UndergroundSpawnAnimation; - PreviousAttack = BrainAIState.Idle; - SpawnDelay = SummonedViaItem ? 2 : 60; - if (SummonedViaItem) - SpawnTime = -1; - - if (Main.netMode != NetmodeID.MultiplayerClient) - { - int brainOfCthuluCreepersCount = GetBrainOfCthuluCreepersCountRevDeath(); - for (int i = 0; i < brainOfCthuluCreepersCount; i++) - NPC.NewNPC(NPC.GetSource_FromAI(), (int)NPC.Center.X, (int)NPC.Center.Y, NPCID.Creeper, NPC.whoAmI, i, ai2: -1); - } - } - - public override bool AI(Mod mod) - { - // whoAmI variable - NPC.crimsonBoss = NPC.whoAmI; - bool phase2 = AIState >= BrainAIState.Phase2TransitionClosed; - - //Takes more damage in Phase 1 to account for invulnerability phases - if (phase2) - { - NPC.knockBackResist = 0f; - NPC.defense = NPC.defDefense; - - NPC.chaseable = (AIState != BrainAIState.IllusionDash && AIState != BrainAIState.IllusionTrick); - } - else - NPC.defense = (int)(NPC.defDefense * Phase1DefenseMultiplier); - - if (AIState < 0) - NPC.damage = 0; - 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) - { - // Ignore tank players, target low HP players, Brain is smart - CalamityTargetingParameters options = CalamityTargetingParameters.BossDefaults; - options.aggroRatio = -1f; - options.finishThemOff = true; - CalamityUtils.CalamityTargeting(NPC, options); - } - - Player target = Main.player[NPC.target]; - #endregion - - #region Despawn - // Despawn check - bool despawn = (target.dead || !target.ZoneCrimson) && !BossRushEvent.BossRushActive; - - // Despawn - if (despawn) - { - if (DespawnTime < 90) - DespawnTime += 1f; - - if (DespawnTime == 90) - NPC.velocity.Y += 0.1f; - } - else if (DespawnTime > 0f) - DespawnTime -= 1f; - - if (Main.netMode != NetmodeID.MultiplayerClient) - { - if (target.Distance(NPC.Center) > DespawnRange) - { - NPC.active = false; - NPC.life = 0; - - if (Main.dedServ) - NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, NPC.whoAmI, 0f, 0f, 0f, 0, 0, 0); - } - } - - if(DespawnTime > 60) - return false; - #endregion - - #region Hit Sounds - if (AIState == BrainAIState.Stunned) - NPC.HitSound = StunnedHit; - else - NPC.HitSound = SoundID.NPCHit9; - #endregion - - #region Health Ratios - float CreeperHPRatio = 0f; - foreach (NPC creeper in Main.npc.Where(n => n.active && n.type == NPCID.Creeper)) - CreeperHPRatio += creeper.life / (float)creeper.lifeMax; - if (CreeperHPRatio != 0f) - CreeperHPRatio /= GetBrainOfCthuluCreepersCountRevDeath(); - - float CreeperAmountRatio = NPC.CountNPCS(NPCID.Creeper) / (float)GetBrainOfCthuluCreepersCountRevDeath(); - #endregion - - #region Forced State Changes - if (!phase2 && CreeperHPRatio == 0f && AIState != BrainAIState.Stunned && AIState >= 0) - { - AIState = BrainAIState.Stunned; - Time = 0; - ResetAttackValues(); - foreach(Projectile p in Main.ActiveProjectiles) - { - if (p.type != ModContent.ProjectileType()) - continue; - - p.ai[1] = 0; - } - } - - if (AIState == BrainAIState.Stunned && (NPC.life / (float)NPC.lifeMax) < Phase2HealthGate) - { - AIState = BrainAIState.Phase2TransitionClosed; - Time = 0; - TeleportTime = 0; - } - #endregion - - switch (AIState) - { - #region Spawn Animations - case BrainAIState.UndergroundSpawnAnimation: - case BrainAIState.SurfaceSpawnAnimation: - if (SpawnTime != 0) //BoC should begin appearing - { - float d = Main.LocalPlayer.DistanceSQ(NPC.Center); - float distanceScaleFactor = 1; - if (d > 592900) //770^2 - distanceScaleFactor = 1 / (1 + (((float)Math.Sqrt(d) - 770) / 32f)); - - float spawnCounter = Time - Math.Abs(SpawnTime); - - if (spawnCounter < 180) - { - float shakeIntensity = CalamityUtils.CircOutEasing(spawnCounter / 180f, 1) * 3f * distanceScaleFactor; - Main.LocalPlayer.SetScreenshake(shakeIntensity); - for (int i = 0; i < shakeIntensity; i++) - { - Point start = target.Center.ToTileCoordinates() + new Point(Main.rand.Next(-64, 65), 48); - for (int j = 0; j < 96; j++) - { - Point current = start - new Point(0, j); - if (!Main.tile[current].IsTileSolid() && Main.tile[current - new Point(0, 1)].TileType == TileID.Crimstone) - Dust.NewDust(current.ToWorldCoordinates(0, -16), 16, 16, DustID.Crimstone, 0, 3); - } - } - } - if (spawnCounter == 180) - NPC.velocity = Vector2.UnitY * (AIState == BrainAIState.UndergroundSpawnAnimation ? 32 : -50); - else if (spawnCounter > 180) - { - NPC.velocity *= 0.955f; - - if (spawnCounter == 240) - { - SoundEngine.PlaySound(IntroRoar, NPC.Center); - - if (Main.netMode == NetmodeID.SinglePlayer) - Main.NewText(Language.GetTextValue("Announcement.HasAwoken", NPC.TypeName), 175, 75); - else if (Main.dedServ) - ChatHelper.BroadcastChatMessage(NetworkText.FromKey("Announcement.HasAwoken", NPC.TypeName), new Color(175, 75, 255)); - } - - if (spawnCounter > 240 && spawnCounter < 390) - { - RevBoCSystem.ScreenBlurStrength = 0.5f;// 0.5f; - if (spawnCounter < 250) - RevBoCSystem.ScreenBlurStrength = MathHelper.Lerp(0, 0.5f, (spawnCounter - 240) / 10f); - - NPC.frameCounter += 1f; - - BoCDrawOffset = Main.rand.NextVector2Circular(4, 4); - - for (int i = 0; i < 3; i++) - { - Point start = target.Center.ToTileCoordinates() + new Point(Main.rand.Next(-64, 65), 48); - for (int j = 0; j < 96; j++) - { - Point current = start - new Point(0, j); - if (!Main.tile[current].IsTileSolid() && Main.tile[current - new Point(0, 1)].TileType == TileID.Crimstone) - Dust.NewDust(current.ToWorldCoordinates(0, -16), 16, 16, DustID.Crimstone, 0, 3); - } - } - - Main.LocalPlayer.SetScreenshake(6 * RevBoCSystem.ScreenBlurStrength * distanceScaleFactor); - - if (spawnCounter % 15 == 0) - { - BossRoar pulse = new(NPC.Center, Color.Black, Main.rand.NextFloatDirection(), 0.1f, 3f, 30); - GeneralParticleHandler.SpawnParticle(pulse); - } - } - else if (spawnCounter >= 390 && spawnCounter <= 420) - { - RevBoCSystem.ScreenBlurStrength = MathHelper.Lerp(0.5f, 0f, (spawnCounter - 390) / 30f); - BoCDrawOffset *= 0.75f; - } - else if (spawnCounter > 420) - { - RevBoCSystem.ScreenBlurStrength = 0f; - BoCDrawOffset = Vector2.Zero; - AIState = BrainAIState.Idle; - ResetAttackValues(); - Time = -1; - SpawnTime = -1; - Main.musicFade[Main.curMusic] = 1f; - break; - } - } - } - if (AttackCounter < GetBrainOfCthuluCreepersCountRevDeath()) - { - if (SpawnTime == 0) - NPC.Center = target.Center + Vector2.UnitY * (AIState == BrainAIState.UndergroundSpawnAnimation ? -900 : 900); - - 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); - else - { - creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1).ToList(); - rand = Main.rand.Next(creepers.Count); - } - - if (creepers.Count > 0) - { - NPC creeper = creepers[rand]; - creeper.AIOverride().Time = 0; - - AttackCounter++; - - if (SummonedViaItem) - SpawnDelay = 2; - else - switch (AttackCounter) - { - case 1: - SpawnDelay = 90; - break; - case 2: - case 3: - case 4: - SpawnDelay = 24; - break; - case 5: - SpawnDelay = 60; - break; - case 6: - case 7: - case 8: - SpawnDelay = 24; - break; - case 9: - SpawnDelay = 60; - break; - default: - SpawnDelay = 4; - break; - } - } - else - SpawnTime = Time; - } - else - SpawnDelay--; - } - else if (SpawnTime == 0) - SpawnTime = Time; - break; - #endregion - - #region Phase 1 - case BrainAIState.Idle: - float speed; - - #region Attack Selection - if (CreeperHPRatio <= DesperateOnslaughtCreeperHealthGate) - { - Time = -1; - AIState = BrainAIState.DesperateOnslaught; - AttackSign = Main.rand.NextBool() ? -1 : 1; - NPC.netUpdate = true; - } - else if (Time > IdlePeriodDuration) - { - Time = -1; - - ResetAttackValues(); - - if (availableAttacks.Count == 0) - { - availableAttacks = [BrainAIState.CreeperSwipes, BrainAIState.CreeperCrush, BrainAIState.CreeperOrbit, BrainAIState.CreeperSpiral]; - if (PreviousAttack != BrainAIState.Idle) - availableAttacks.Remove(PreviousAttack); - } - - int pick = Main.rand.Next(availableAttacks.Count); - AIState = availableAttacks[pick]; - availableAttacks.RemoveAt(pick); - PreviousAttack = AIState; - - foreach (NPC creep in Main.npc.Where(n => n.active && n.type == NPCID.Creeper)) - creep.AIOverride().Time = -1; - - NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } - } - #endregion - - /* - #region Creeper Attacks - if (AttackCounter > 0) - AttackCounter--; - else if (Time < IdlePeriodDuration - 120) - { - if (Time >= 30) - { - bool targetLeft = target.Center.X < NPC.Center.X; - List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1 && n.AIOverride().CreeperID % 2 == (targetLeft ? 0 : 1)).ToList(); - if (creepers.Count == 0) - creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1).ToList(); - - if (creepers.Count > 0) - { - int rand = Main.rand.Next(creepers.Count); - - NPC creeper = creepers[rand]; - creeper.AIOverride().Time = 0; - } - } - AttackCounter = (int)MathHelper.Lerp(CreeperChargeDelayMax, CreeperChargeDelayMin, 1 - CreeperAmountRatio); - } - #endregion - */ - - #region Movement - if (Time == 0) - { - AttackSign = Main.rand.NextBool() ? -1 : 1; - NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } - } - - float rotateDir = AttackSign; - Vector2 fromTarget = NPC.DirectionFrom(target.Center); - Vector2 dir = fromTarget.RotatedBy(Math.Sin(Time / 60f) * rotateDir) * new Vector2(2, 1); - float rayDist = CalamityUtils.PreciseDistanceToTileCollisionHit(target.Center, dir.ToRotation(), 360, 1); - Vector2 offset = dir * (rayDist - NPC.width); - Vector2 goalPos = target.Center + offset; - float distSQ = NPC.DistanceSQ(goalPos); - if (distSQ > 129600) - { - NPC.velocity = NPC.DirectionTo(goalPos) * (4 + (NPC.Distance(goalPos) - 360) / 64f); - } - else if (distSQ <= 2048) - { - NPC.velocity *= 0.9f; - } - else if (NPC.velocity.LengthSquared() < 16f) - { - NPC.velocity += NPC.DirectionTo(goalPos).SafeNormalize(Vector2.Zero) * 0.15f; - } - else - { - NPC.velocity = NPC.DirectionTo(goalPos).SafeNormalize(Vector2.Zero) * 6f; - } - #endregion - - break; - case BrainAIState.DesperateOnslaught: - #region Movement - if (Collision.SolidCollision(NPC.position, NPC.width, NPC.height)) - { - NPC.velocity = NPC.DirectionTo(target.Center) * 4f; - Time = -1; - } - else if (NPC.DistanceSQ(target.Center) > 230400) - NPC.velocity = NPC.DirectionTo(target.Center) * (NPC.Distance(target.Center) - 480) / 128f; - else - NPC.velocity *= 0.9f; - #endregion - - float wrappedCounter = Time % 90; - - if (Time <= 60) - { - if (Time == 0) - SoundEngine.PlaySound(Roar, NPC.Center); - if (Time < 30) - { - RevBoCSystem.ScreenBlurStrength = 0.5f; - - NPC.frameCounter += 1f; - - for (int i = 0; i < 3; i++) - { - Point start = target.Center.ToTileCoordinates() + new Point(Main.rand.Next(-64, 65), 48); - for (int j = 0; j < 96; j++) - { - Point current = start - new Point(0, j); - if (!Main.tile[current].IsTileSolid() && Main.tile[current - new Point(0, 1)].TileType == TileID.Crimstone) - Dust.NewDust(current.ToWorldCoordinates(0, -16), 16, 16, DustID.Crimstone, 0, 3); - } - } - - float d = Main.LocalPlayer.DistanceSQ(NPC.Center); - float distanceScaleFactor = 1; - if (d > 592900) //770^2 - distanceScaleFactor = 1 / (1 + (((float)Math.Sqrt(d) - 770) / 32f)); - - Main.LocalPlayer.SetScreenshake(4 * RevBoCSystem.ScreenBlurStrength * distanceScaleFactor); - - if (Time % 15 == 0) - { - BossRoar pulse = new(NPC.Center, Color.Black, Main.rand.NextFloatDirection(), 0.1f, 3f, 30); - GeneralParticleHandler.SpawnParticle(pulse); - } - } - else - { - RevBoCSystem.ScreenBlurStrength = MathHelper.Lerp(0.5f, 0, CalamityUtils.CircOutEasing((Time - 30) / 30f, 1)); - } - } - else - { - RevBoCSystem.ScreenBlurStrength = 0f; - if (wrappedCounter == 65) - { - int checkCount = 8; - float wallDist = CalamityUtils.PreciseDistanceToTileCollisionHit(NPC.Center, AttackSign == -1 ? MathHelper.Pi : 0, 480 + NPC.width) - NPC.width; - Vector2[] starts = new Vector2[checkCount]; - for (int i = 0; i < checkCount; i++) - { - float completion = (i + 1) / (float)(checkCount + 1); - starts[i] = NPC.Center + (Vector2.UnitX * ((wallDist * completion) + NPC.width) * AttackSign); - } - - Vector2[] ends = new Vector2[checkCount]; - List goodEnds = []; - List farEnds = []; - List closeEnds = []; - - for (int i = 0; i < checkCount; i++) - { - float maxDist = 960; - float floorDist = CalamityUtils.PreciseDistanceToTileCollisionHit(NPC.Center, Vector2.UnitY.ToRotation(), maxDist); - ends[i] = starts[i] + (Vector2.UnitY * (floorDist + 48)); - if (floorDist >= 600) - farEnds.Add(ends[i]); - else if (floorDist > 240) - goodEnds.Add(ends[i]); - else - closeEnds.Add(ends[i]); - } - - Vector2 chosenEnd; - - if (goodEnds.Count > 0) - chosenEnd = goodEnds[Main.rand.Next(goodEnds.Count)]; - else if (closeEnds.Count > 0) - chosenEnd = closeEnds[Main.rand.Next(closeEnds.Count)]; - else - chosenEnd = farEnds[Main.rand.Next(farEnds.Count)]; - - if (Main.netMode != NetmodeID.MultiplayerClient) - Projectile.NewProjectile(NPC.GetSource_FromThis(), chosenEnd, Vector2.Zero, ModContent.ProjectileType(), 10, 0.5f); - - AttackSign *= -1; - } - } - break; - case BrainAIState.Stunned: - #region Movement - NPC.velocity = NPC.velocity.ClampMagnitude(0f, 6f); - fromTarget = (NPC.Center - target.Center).SafeNormalize(Vector2.UnitX); - if (Time == 0) - { - NPC.velocity = fromTarget * 4f; - SoundEngine.PlaySound(ShieldDown, NPC.Center); - } - - if (NPC.velocity != Vector2.Zero) - { - if (Time >= StunDuration) - NPC.velocity *= 0.8f; - else - NPC.velocity *= 0.93f; - } - - if (Time < StunDuration) - NPC.position.Y += (float)Math.Sin(Time / 8f) * 2 * (1 - MathHelper.Clamp((Time - (StunDuration - 30)) / 30f, 0f, 1f)); - - if (Time <= StunDuration - 30) - { - if (AttackTime > 0) - { - float kbCounter = 30 - AttackTime; - if (kbCounter < 10) - { - float lerp = CalamityUtils.SineOutEasing(kbCounter / 10f, 1); - NPC.rotation = AttackRotation.AngleLerp(-AttackRotation, lerp); - } - else - { - float lerp = CalamityUtils.SineInOutEasing((kbCounter - 10) / 20f, 1); - NPC.rotation = (-AttackRotation).AngleLerp(0, lerp); - } - - } - else if (Math.Abs(NPC.oldVelocity.X) < Math.Abs(NPC.velocity.X) || Time <= 0) - { - AttackRotation = NPC.rotation; - TeleportTime = 0; - } - else - { - TeleportTime++; - NPC.rotation = MathHelper.Lerp(AttackRotation, MathHelper.Pi / 24f * NPC.oldVelocity.X, CalamityUtils.CircOutEasing(MathHelper.Clamp(TeleportTime / 30f, 0f, 1f), 1)); - } - } - #endregion - - #region Tile Collision - if (Time < StunDuration) - { - if (Collision.SolidCollision(NPC.position, NPC.width, NPC.height)) - { - NPC.velocity = NPC.DirectionTo(target.Center) * 4f; - } - else if (Collision.SolidCollision(NPC.position + NPC.velocity, NPC.width, NPC.height)) - { - if (NPC.velocity.X != NPC.oldVelocity.X) - NPC.velocity.X = -NPC.oldVelocity.X; - if (NPC.velocity.Y != NPC.oldVelocity.Y) - NPC.velocity.Y = -NPC.oldVelocity.Y; - //NPC.velocity *= 2f; - NPC.velocity = NPC.velocity.ClampMagnitude(0f, 8f); - AttackTime = 30; - AttackRotation = NPC.rotation; - } - - if (AttackTime > 0) - { - NPC.knockBackResist = 0f; - AttackTime--; - if (AttackTime == 0) - { - NPC.velocity = Vector2.Zero; - AttackRotation = 0; - } - } - else - NPC.knockBackResist = 1f; - } - #endregion - - RevBoCSystem.ScreenBlurStrength = 0f; - - NPC.dontTakeDamage = false; - - if (Time <= 15) - { - float lerp = Time / 15f; - ShieldOpacity = 1 - CalamityUtils.CircOutEasing(lerp, 1); - ShieldScale = MathHelper.Lerp(1f, 1.5f, lerp); - } - - #region Recovery - if (OnSecondCreeperPhase && Time == StunDuration - 30) - { - AIState = BrainAIState.Phase2TransitionClosed; - Time = -1; - TeleportTime = 0; - break; - } - - if (Time > StunDuration - 30) - { - NPC.rotation = NPC.rotation.AngleLerp(0f, CalamityUtils.SineInOutEasing((Time - (StunDuration - 30)) / 30f, 1)); - if (Time == StunDuration - 15) - SoundEngine.PlaySound(ShieldUp, NPC.Center); - } - - if (Time >= StunDuration) - { - if (NPC.velocity.X < 0.001f && NPC.velocity.X < 0.001f) - NPC.velocity = Vector2.Zero; - - int creeperRate = 5; - wrappedCounter = (Time - StunDuration) % creeperRate; - int spawnTime = GetBrainOfCthuluCreepersCountRevDeath() / 2 * creeperRate; - - if (Time == StunDuration) - AttackCounter = GetBrainOfCthuluCreepersCountRevDeath() - 1; - - NPC.knockBackResist = 0f; - NPC.dontTakeDamage = true; - NPC.rotation = 0f; - - float shieldAppearTime = 15f; - - float lerp = MathHelper.Clamp((Time - StunDuration) / shieldAppearTime, 0f, 1f); - if (lerp >= 1) - { - ShieldOpacity = 1f; - ShieldScale = 1f; - } - else - { - ShieldOpacity = CalamityUtils.CircOutEasing(lerp, 1); - ShieldScale = MathHelper.Lerp(1.5f, 1f, CalamityUtils.SineOutEasing(lerp, 1)); - } - - if (AttackCounter == -1 && Time > StunDuration + spawnTime + 30) - { - OnSecondCreeperPhase = true; - AIState = BrainAIState.Idle; - Time = -1; - } - else if (AttackCounter > -1 && wrappedCounter == 0) - { - for (int i = 0; i < 2; i++) - { - dir = Vector2.UnitY.RotatedBy((AttackCounter % 2 == 0 ? 1 : -1) * (MathHelper.Pi / 16f + ((MathHelper.Pi - MathHelper.Pi / 8f) * (AttackCounter / 2f / (GetBrainOfCthuluCreepersCountRevDeath() / 2f))))); - Vector2 spawnPos = NPC.Center + (dir * 72f); - if (Main.netMode != NetmodeID.MultiplayerClient) - { - NPC creeper = NPC.NewNPCDirect(NPC.GetSource_FromAI(), spawnPos, NPCID.Creeper, NPC.whoAmI, AttackCounter, ai2: -1, ai3: 1); - creeper.velocity = dir * 24f; - } - - for (int j = 0; j < 3; j++) - { - BloodParticle p = new(spawnPos, dir.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 6f, MathHelper.Pi / 6f)) * Main.rand.NextFloat(8f, 12f), 32, 1f, Color.Red); - GeneralParticleHandler.SpawnParticle(p); - } - BloodParticle2 p2 = new(spawnPos, dir * 10f, 16, 0.5f, Color.Red); - GeneralParticleHandler.SpawnParticle(p2); - - if (!Main.dedServ) - { - RevBoCSystem.VerletTendrils[(int)AttackCounter] = []; - for (int j = 0; j < 28; j++) - RevBoCSystem.VerletTendrils[(int)AttackCounter].Add(new(NPC.Center)); - } - - AttackCounter--; - if (AttackCounter <= -1) - break; - } - - SoundEngine.PlaySound(SoundID.NPCHit9, NPC.Center); - } - } - #endregion - - break; - case BrainAIState.CreeperSwipes: - //Hand Size check to determine if 1 hand variant should be used - if (Time == 0) - { - int leftAmt = 0; - int rightAmt = 0; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - - if (creeper.AIOverride().CreeperID % 2 == 0) - leftAmt++; - else - rightAmt++; - } - - if (leftAmt > 5 && rightAmt > 5) - { - AttackSign = Main.rand.NextBool() ? -1 : 1; - AttackFlag = false; - } - else - AttackFlag = true; - - NPC.netUpdate = true; - AttackList.Clear(); - } - - float wrappedCount = Time % (SwipeDuration + SwipeDelay); - - if (Time >= SwipesStartupDuration) - { - NPC.damage = NPC.defDamage; - if (wrappedCount == 0) - { - bool useEven = Main.rand.NextBool(); - - bool anyActivated = false; - - foreach (NPC Npc in Main.ActiveNPCs) - { - if (Npc.type != NPCID.Creeper) - continue; - - if (AttackFlag || Npc.AIOverride().CreeperID % 2 == 0! ^ useEven) - { - AttackList.Add(Npc.whoAmI); - //Npc.AIOverride().Time = 0; - anyActivated = true; - } - } - - if (!anyActivated) - foreach (NPC Npc in Main.ActiveNPCs) - { - if (Npc.type != NPCID.Creeper) - continue; - - AttackList.Add(Npc.whoAmI); - //Npc.AIOverride().Time = 0; - } - - NPC.netUpdate = true; - } - else if (wrappedCount == SwipeDuration) - { - AttackSign *= -1; - AttackList.Clear(); - NPC.netUpdate = true; - } - - if (wrappedCount > 1 && wrappedCount <= SwipeIchorDelay && Time % 3 == 0) // Telegraphs ichor rain w/ dripping particles - { - Vector2 spawnPosition = NPC.Center; - spawnPosition.Y += Main.rand.NextFloat(38, 50); - spawnPosition.X += Main.rand.NextFloat(-56, 56); - - BloodParticle blood = new BloodParticle(spawnPosition, Main.rand.NextVector2Unit() * Main.rand.NextFloat(1.5f, 2.5f), Main.rand.Next(30, 40), Main.rand.NextFloat(0.6f, 1f), Color.Gold); - GeneralParticleHandler.SpawnParticle(blood); - } - - if (wrappedCount < 60f) // Vibrates during telegraph - { - Vector2 vibrationVector = Main.rand.NextVector2CircularEdge(1, 1) * MathHelper.Lerp(0f, 12f, CalamityUtils.CircInEasing(wrappedCount / 80f, 1)); - - BoCDrawOffset = vibrationVector; - } - else if (wrappedCount > 60f && wrappedCount < 80f) // Droops down when starting to fire ichor shots - { - float progress = (wrappedCount - 60f) / 20f; - BoCDrawOffset = new Vector2(0, MathHelper.Lerp(10, 0, 1f - (float)Math.Pow(1f - progress, 3f))); - } - - if (Main.netMode != NetmodeID.MultiplayerClient) - if (wrappedCount > SwipeIchorDelay && wrappedCount <= SwipeDuration && Time % 2 == 0) - Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center + new Vector2(Main.rand.NextFloat(-72, 72), 56), Vector2.UnitY.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 4f, MathHelper.Pi / 4f)) * 4f, ProjectileID.GoldenShowerHostile, IchorShotDamage, 0.5f); - - if (Time >= SwipesStartupDuration + ((SwipeDuration + SwipeDelay) * SwipeAmount)) - { - Time = 0; - AIState = BrainAIState.Idle; - NPC.netUpdate = true; - AttackList.Clear(); - } - } - else - NPC.damage = 0; - - #region Movement - goalPos = target.Center + (Vector2.UnitY * -270); - distSQ = NPC.DistanceSQ(goalPos); - if ((Time > SwipesStartupDuration && wrappedCount > 30 && wrappedCount <= SwipeDuration) || NPC.DistanceSQ(goalPos) <= 2048) - NPC.velocity *= 0.9f; - else if (distSQ > 14400) - NPC.velocity = NPC.DirectionTo(goalPos) * (8 + (NPC.Distance(goalPos) - 120) / 16f); - else - NPC.velocity = NPC.DirectionTo(goalPos).SafeNormalize(Vector2.UnitX * -target.direction) * (8f * distSQ / 14400f); - #endregion - break; - case BrainAIState.CreeperCrush: - #region Movement - Vector2 goalDir = Vector2.Zero; - fromTarget = NPC.Center - target.Center; - if (Math.Abs(fromTarget.X) > Math.Abs(fromTarget.Y)) - goalDir = Vector2.UnitX * Math.Sign(fromTarget.X); - else - goalDir = Vector2.UnitY * Math.Sign(fromTarget.Y); - - goalPos = target.Center + (goalDir * 360) - (Vector2.UnitY * 32); - if (NPC.DistanceSQ(goalPos) <= 2048) - NPC.velocity *= 0.9f; - else if (NPC.velocity.LengthSquared() <= 56.25f) //7.5^2 - NPC.velocity += NPC.DirectionTo(goalPos).SafeNormalize(Vector2.UnitX * -target.direction) * 0.5f; - else - NPC.velocity = NPC.DirectionTo(goalPos).SafeNormalize(Vector2.UnitX * -target.direction) * 8f; - #endregion - - float delay = OnSecondCreeperPhase ? StrongSwipeDelay : LightSwipeDelay; - if(Time == 0) - AttackList.Clear(); - - 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))) - creeper.position += NPC.velocity; - - int crushCount; - int attackDelay; - if (!OnSecondCreeperPhase) - { - crushCount = LightSwipeAmount; - attackDelay = LightSwipeDuration; - } - else - { - crushCount = StrongSwipeAmount; - attackDelay = StrongSwipeDuration; - } - int attackDur = attackDelay * crushCount; - - 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(); - if (creepers.Count > 1) - { - float rotation; - if (!OnSecondCreeperPhase) - { - rotation = target.velocity.ToRotation(); - if (target.velocity == Vector2.Zero) - rotation = target.direction == 1 ? 0 : MathHelper.Pi; - rotation += Main.rand.NextFloat(-MathHelper.PiOver4 / 2f, MathHelper.PiOver4 / 2f); - } - else - rotation = Main.rand.NextFloat(0, MathHelper.TwoPi); - - int rand = Main.rand.Next(creepers.Count); - NPC first = creepers[rand]; - CreeperAI creeper1 = first.AIOverride(); - AttackList.Add(first.whoAmI); - //creeper1.Time = 0; - creeper1.AttackAngle = rotation; - creepers.RemoveAt(rand); - - NPC second = creepers[Main.rand.Next(creepers.Count)]; - CreeperAI creeper2 = second.AIOverride(); - AttackList.Add(second.whoAmI); - //creeper2.Time = 0; - creeper2.AttackAngle = rotation + MathHelper.Pi; - - creeper1.PartnerIndex = second.whoAmI; - creeper2.PartnerIndex = first.whoAmI; - } - - NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } - } - - if (Time > delay + attackDur + attackDelay) - { - Time = 0; - AIState = BrainAIState.Idle; - AttackList.Clear(); - //foreach (NPC creep in Main.npc.Where(n => n.active && n.type == NPCID.Creeper)) - // creep.AIOverride().Time = -1; - } - } - break; - case BrainAIState.CreeperOrbit: - #region Movement - fromTarget = (NPC.Center - target.Center).SafeNormalize(Vector2.UnitX); - goalPos = target.Center + (fromTarget * 440) - (Vector2.UnitY * 32); - distSQ = NPC.DistanceSQ(goalPos); - if (distSQ > 14400) - NPC.velocity = NPC.DirectionTo(goalPos) * (4 + (NPC.Distance(goalPos) - 120) / 16f); - else - NPC.velocity = NPC.DirectionTo(goalPos).SafeNormalize(Vector2.Zero) * (2 + (2f * (distSQ / 14400))); - #endregion - - if (Time == 0) - { - AttackSign = Main.rand.NextBool() ? -1 : 1; - NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } - } - - if (Time >= OrbitDuration + 30) - { - Time = -1; - AIState = BrainAIState.Idle; - AttackList.Clear(); - foreach (NPC creep in Main.ActiveNPCs) - { - if (creep.type == NPCID.Creeper) - creep.AIOverride().Time = -1; - } - } - else if (Time >= OrbitAttackInterval && Time < OrbitDuration && Time % OrbitAttackInterval == 0) - { - List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper).ToList(); - if (creepers.Count > 0) - { - int rand = Main.rand.Next(creepers.Count); - for (int i = 0; i < OrbitAttackParticipantCount; i++) - { - if (rand >= creepers.Count) - rand -= creepers.Count; - NPC creeper = creepers[rand]; - AttackList.Add(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; - } - } - } - break; - case BrainAIState.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); - float timePerRev = MathHelper.Lerp(startTimePerRev, endTimePerRev, MathHelper.Clamp((Time - SpeedUpDelayTime) / (SpiralDuration - SpeedUpDelayTime - SpeedUpExtensionTime), 0f, 1f)); - if (Time > SpiralDuration - 30) - timePerRev *= MathHelper.Lerp(1f, 10f, CalamityUtils.CircOutEasing((Time - (SpiralDuration - 30)) / 30f, 1)); - else if (Time < SpiralSetupTime) - timePerRev *= MathHelper.Lerp(1f, 10f, CalamityUtils.CircInEasing(Time / SpiralSetupTime, 1)); - - float rotToAdd = MathHelper.TwoPi / timePerRev * AttackSign; - if (OnSecondCreeperPhase) - { - float attackComplationRatio = Time / SpiralDuration; - float lerp = Utils.GetLerpValue(TurnAroundRatio - (TurnAroundDurationRatio / 2f), TurnAroundRatio + (TurnAroundDurationRatio / 2f), attackComplationRatio, true); - rotToAdd *= MathHelper.Lerp(1, -1, lerp); - } - AttackRotation += rotToAdd; - - if (NPC.DistanceSQ(target.Center) > 57600) - NPC.velocity = NPC.DirectionTo(target.Center) * (NPC.Distance(target.Center) - 240) / 32f; - else - NPC.velocity *= 0.9f; - - if (Time > SpiralDuration) - { - Time = -1; - AIState = BrainAIState.Idle; - foreach (NPC creep in Main.ActiveNPCs) - { - if (creep.type == NPCID.Creeper) - creep.AIOverride().Time = -1; - } - } - break; - #endregion - - #region Phase Transition - case BrainAIState.Phase2TransitionClosed: - case BrainAIState.Phase2TransitionOpen: - NPC.dontTakeDamage = true; - NPC.rotation *= 0.9f; - TeleportTime = 0; - - float animCounter = Time - 60; - if (animCounter >= 0) - { - if (animCounter == 0) - NPC.velocity = Vector2.UnitY * 2f; - else if (animCounter < 60) - NPC.velocity *= 0.99f; - else if (animCounter == 60) - NPC.velocity = Vector2.UnitY * -8f; - else if (animCounter == 65) - { - AIState = BrainAIState.Phase2TransitionOpen; - PreviousAttack = BrainAIState.Idle; - availableAttacks.Clear(); - - SoundEngine.PlaySound(SoundID.NPCHit1, NPC.Center); - - if (!Main.dedServ) - { - //Spawns all of BoC's Phase Transition Gores (GoreIDs 392 -> 395) - for (int i = 392; i <= 395; i++) - Gore.NewGore(NPC.GetSource_FromAI(), NPC.position, Main.rand.NextVector2Circular(6f, 6f), i); - } - - for (int j = 0; j < 20; j++) - Dust.NewDustPerfect(Main.rand.NextVector2FromRectangle(NPC.Hitbox), DustID.Blood, Main.rand.NextVector2Circular(6f, 6f)); - - for (int i = 1; i <= 3; i++) - { - Color color = i switch - { - 1 => Color.Yellow, - 2 => Color.Orange, - _ => Color.Red, - }; - PulseRing ring = new(NPC.Center, NPC.velocity * 0.5f, color, 0f, 1f + i * 0.5f, 24); - GeneralParticleHandler.SpawnParticle(ring); - } - - BoCAfterImages = []; - - SoundEngine.PlaySound(Roar, NPC.Center); - } - else - NPC.velocity *= 0.9f; - - if (animCounter < 60f) - BoCDrawOffset = Main.rand.NextVector2CircularEdge(1, 1) * MathHelper.Lerp(0f, 16f, CalamityUtils.CircInEasing(animCounter / 60f, 1)); - else if (animCounter < 70f) - BoCDrawOffset = Main.rand.NextVector2CircularEdge(1, 1) * MathHelper.Lerp(16f, 0f, CalamityUtils.CircOutEasing((animCounter - 60) / 10f, 1)); - - if (animCounter >= 120f) - { - Time = 0; - ResetAttackValues(); - AIState = BrainAIState.Phase2Idle; - NPC.dontTakeDamage = false; - } - } - else - { - NPC.velocity *= 0.8f; - - #region Tile Collision - if (Collision.SolidCollision(NPC.position, NPC.width, NPC.height)) - { - NPC.velocity = NPC.DirectionTo(target.Center) * 4f; - } - else if (Collision.SolidCollision(NPC.position + NPC.velocity, NPC.width, NPC.height)) - { - if (NPC.velocity.X != NPC.oldVelocity.X) - NPC.velocity.X = -NPC.oldVelocity.X; - if (NPC.velocity.Y != NPC.oldVelocity.Y) - NPC.velocity.Y = -NPC.oldVelocity.Y; - NPC.velocity *= 2f; - NPC.velocity = NPC.velocity.ClampMagnitude(0f, 8f); - } - #endregion - } - break; - #endregion - - #region Phase 2 - case BrainAIState.Phase2Idle: - //goes from 3 at full health to 1 at low health - int chases = (int)Math.Ceiling(MaxChases * (NPC.life / (float)NPC.lifeMax)); - - NPC.rotation = NPC.velocity.X / 6f * MathHelper.Pi / 8f; - - if(Time == ChaseTime - 5) - AttackCounter++; - - if (Time <= ChaseTime) - { - float speedUp = MathHelper.Clamp((Time - 10) / 10f, 0f, 1f); - float slowDown = 1 - MathHelper.Clamp((Time - (ChaseTime - 15)) / 15f, 0f, 1f); - float angleChange = MathHelper.Lerp(MathHelper.Pi / 24f, 0f, MathHelper.Clamp(Time / (ChaseTime * 0.666f), 0f, 1f)); - NPC.velocity = NPC.velocity.RotateDirectionTowards(NPC.DirectionTo(target.Center).ToRotation(), angleChange) * (MathHelper.Lerp(3f, 18f, Time / ChaseTime) * speedUp * slowDown); - - if (Time == ChaseTime) - { - Vector2 direction = target.velocity.SafeNormalize(Vector2.UnitX * target.direction).RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 3f, MathHelper.Pi / 3f)); - AttackPosition = target.Center + (direction * DefaultTeleportDistance); - BoCAfterImages = []; - NPC.netUpdate = true; - } - else - { - TeleportTime = 0; - NPC.Opacity = 1f; - } - } - else - { - TeleportDuration = IdleTeleportDuration; - - Vector2 endPoint = AttackPosition; - - NPC.velocity = Vector2.Zero; - - if (Time < ChaseTime + (TeleportDuration / 2f)) - { - if (Time % 4 == 0) - { - Vector2 startPoint = NPC.Center; - - Vector2 direction = endPoint - startPoint; - float curveIntensity = Main.rand.NextFloat(-0.2f, 0.2f); - Vector2 perpindicular = direction.RotatedBy(MathHelper.PiOver2); - - Vector2 controlPoint1 = startPoint + (direction * 0.25f) + (perpindicular * curveIntensity); - Vector2 controlPoint2 = startPoint + (direction * 0.75f) + (perpindicular * curveIntensity); - - BezierCurve path = new BezierCurve(startPoint, controlPoint1, controlPoint2, endPoint); - - BrainofCthulhuAfterImage afterimage = new(path, NPC.rotation, Vector2.One, (int)(ChaseTime + (TeleportDuration * 0.75f) - Time), BoCFrame); - BoCAfterImages.Add(afterimage); - GeneralParticleHandler.SpawnParticle(afterimage); - } - TeleportTime++; - } - else if (Time == ChaseTime + (TeleportDuration / 2f) && !AttackFlag) - { - Vector2 start = NPC.Center; - NPC.Center = endPoint; - AttackFlag = true; - NPC.netUpdate = true; - } - else - { - TeleportTime--; - if (TeleportTime < 0) - { - TeleportTime = 0; - Time = -1; - AttackFlag = false; - - #region Attack Selection - if (AttackCounter >= chases) //Pick attack - { - NPC.rotation = 0; - ResetAttackValues(); - - if (availableAttacks.Count == 0) - { - bool quickChoice = Main.rand.NextBool(); - availableAttacks = [ - BrainAIState.Bloodletting, - quickChoice ? BrainAIState.SanguineScythes : BrainAIState.IllusionDash, - Main.rand.NextBool() ? BrainAIState.Phase2Idle : BrainAIState.Bloodletting, - quickChoice ? BrainAIState.IllusionDash : BrainAIState.SanguineScythes, - BrainAIState.IllusionTrick - ]; - } - - AIState = availableAttacks[0]; - availableAttacks.RemoveAt(0); - PreviousAttack = AIState; - - if (AIState == BrainAIState.SanguineScythes) - { - Time = -31; - BoCAfterImages = []; - } - - NPC.netUpdate = true; - } - #endregion - } - } - - NPC.Opacity = 1 - (TeleportTime / (TeleportDuration / 2f)); - } - break; - case BrainAIState.Bloodletting: - float endTime = Time - BloodlettingDuration; - - #region Main Attack - if (endTime < 0) - { - NPC.rotation = (float)Math.Sin(Time / 8f) * MathHelper.Pi / 8f; - BoCDrawOffset = Vector2.Zero; - - if (Time > BloodshotRate) //Doesnt fire first bloodshot - { - if (Time % IchorRate == 0) - { - if (Time % (IchorRate * 2) == 0) - SoundEngine.PlaySound(SoundID.Item17, NPC.Center); - if (Main.netMode != NetmodeID.MultiplayerClient) - Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center + NPC.velocity + Main.rand.NextVector2Circular(72, 72), new Vector2(Main.rand.NextFloat(-IchorSpread, IchorSpread), -IchorVelocity), ModContent.ProjectileType(), IchorShotDamage, 0.5f); - } - - if (Main.netMode != NetmodeID.MultiplayerClient) - if (Time % BloodshotRate == 0) - { - dir = NPC.DirectionTo(target.Center); - - for (int i = -2; i <= 2; i++) - { - Vector2 initialDir = dir.RotatedBy(i * MathHelper.Pi / 4f); - Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, initialDir * BloodshotVelocity, ProjectileID.BloodNautilusShot, BloodShotDamage, 0.5f, ai0: dir.ToRotation() + MathHelper.TwoPi, ai1: initialDir.ToRotation()); - } - - if (death) - { - Vector2 initialDir = dir.RotatedBy(MathHelper.Pi / 6f); - Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, initialDir * BloodshotVelocity / 2f, ProjectileID.BloodNautilusShot, BloodShotDamage, 0.5f, ai0: dir.ToRotation() + MathHelper.TwoPi, ai1: initialDir.ToRotation()); - initialDir = dir.RotatedBy(-MathHelper.Pi / 6f); - Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, initialDir * BloodshotVelocity / 2f, ProjectileID.BloodNautilusShot, BloodShotDamage, 0.5f, ai0: dir.ToRotation() + MathHelper.TwoPi, ai1: initialDir.ToRotation()); - } - } - - - } - } - #endregion - - #region Attack End - else - { - NPC.rotation *= 0.9f; - - if (endTime == 0) - SoundEngine.PlaySound(Roar, NPC.Center); - if (endTime >= DashPrepTime) - { - if (endTime < DashPrepTime + DashReelbackTime) - { - float reelBackSpeedExponent = 2.6f; - float reelBackCompletion = Utils.GetLerpValue(0f, 30, endTime - DashPrepTime, true); - float reelBackSpeed = MathHelper.Lerp(4f, 16f, MathF.Pow(reelBackCompletion, reelBackSpeedExponent)); - Vector2 reelBackVelocity = Vector2.UnitY * -reelBackSpeed; - NPC.velocity = Vector2.Lerp(NPC.velocity, reelBackVelocity, 0.25f); - } - else if (endTime == DashPrepTime + 20) - NPC.velocity = Vector2.UnitY * DashVelocity; - - if (endTime >= DashPrepTime + DashReelbackTime && Time % DashScytheRate == 0) - { - if (Main.netMode != NetmodeID.MultiplayerClient) - { - Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, Vector2.UnitX * 16f, ModContent.ProjectileType(), BloodScytheDamage, 0.5f); - Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, Vector2.UnitX * -16f, ModContent.ProjectileType(), BloodScytheDamage, 0.5f); - } - } - - if (endTime > DashPrepTime + DashReelbackTime + DashDuration) - { - NPC.rotation = 0; - SetupForNextAttack(); - break; - } - } - } - #endregion - - #region Movement - - if (endTime < 0) - { - if (Time == 0) - { - AttackPosition = NPC.Center; - if (NPC.Center.X < target.Center.X) - AttackSign = -1; - else - AttackSign = 1; - } - - float waveValue = Time * MathHelper.Pi / BloodshotRate; - 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; - if (Time < 30f) - NPC.Center = Vector2.Lerp(AttackPosition, goalPos, CalamityUtils.SineOutEasing(Time / 30f, 1)); - else - NPC.Center = goalPos; - } - else if (endTime < DashPrepTime) - { - if (endTime == 0) - NPC.velocity = Vector2.UnitX * AttackSign * 8f; - else - { - goalPos = target.Center - Vector2.UnitY * HoverEndHeight; - Vector2 accel = new Vector2(0.5f, 1.5f); - - NPC.velocity += NPC.DirectionTo(goalPos).SafeNormalize(Vector2.Zero) * accel; - NPC.velocity = NPC.velocity.ClampMagnitude(0f, 8f); - } - } - #endregion - - break; - case BrainAIState.SanguineScythes: - #region Attack Ending - if (AttackCounter > SanguineTeleportCount) - { - if (Time == SanguineAttackEndDelay) - { - SoundEngine.PlaySound(Roar, NPC.Center); - bool left = target.Center.X > NPC.Center.X; - NPC.velocity = Vector2.UnitX * (left ? 18 : -18); - NPC.rotation = MathHelper.Pi / 8f * (left ? 1 : -1); - } - if (Time > SanguineAttackEndDelay + SanguineAttackEndDuration) - { - NPC.velocity *= 0.8f; - NPC.rotation *= 0.8f; - } - else if (Time >= SanguineAttackEndDelay && Time % SanguineAttackEndIchorRate == 0) - { - if (Main.netMode != NetmodeID.MultiplayerClient) - { - Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, new Vector2(Math.Sign(NPC.velocity.X), -2f), ModContent.ProjectileType(), IchorShotDamage, 0.5f); - Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, new Vector2(Math.Sign(NPC.velocity.X), -6f), ModContent.ProjectileType(), IchorShotDamage, 0.5f); - } - } - - if (Time > SanguineAttackEndDelay + SanguineAttackEndDuration + 10) - SetupForNextAttack(); - } - #endregion - #region Attack Start - else if (Time < 0) - { - if(Time == -25) - NPC.netUpdate = true; - - if (Time == -24) - { - SoundEngine.PlaySound(Roar, NPC.Center); - - for (int i = 1; i <= 3; i++) - { - Color color = i switch - { - 1 => Color.Yellow, - 2 => Color.Orange, - _ => Color.Red, - }; - PulseRing ring = new(NPC.Center, NPC.velocity * 0.5f, color, 0f, 1f + i * 0.5f, 24); - GeneralParticleHandler.SpawnParticle(ring); - } - } - if (Time == -1) - { - Vector2 direction = target.velocity.SafeNormalize(Vector2.UnitX * target.direction).RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 3f, MathHelper.Pi / 3f)); - float distance = SanguineTeleportDistance; - AttackPosition = target.Center + (direction * distance); - NPC.netUpdate = true; - } - } - #endregion - #region Teleport - else - { - TeleportDuration = SanguineTeleportDuration; - - Vector2 endPoint = AttackPosition; - - if (Time < (TeleportDuration / 2f)) - { - if (Time % 4 == 0) - { - Vector2 startPoint = NPC.Center; - - Vector2 direction = endPoint - startPoint; - float curveIntensity = Main.rand.NextFloat(-0.2f, 0.2f); - Vector2 perpindicular = direction.RotatedBy(MathHelper.PiOver2); - - Vector2 controlPoint1 = startPoint + (direction * 0.25f) + (perpindicular * curveIntensity); - Vector2 controlPoint2 = startPoint + (direction * 0.75f) + (perpindicular * curveIntensity); - - BezierCurve path = new BezierCurve(startPoint, controlPoint1, controlPoint2, endPoint); - - BrainofCthulhuAfterImage afterimage = new(path, NPC.rotation, Vector2.One, (int)((TeleportDuration * 0.75f) - Time), BoCFrame); - BoCAfterImages.Add(afterimage); - GeneralParticleHandler.SpawnParticle(afterimage); - } - TeleportTime++; - } - else if (Time == (TeleportDuration / 2f) && !AttackFlag) - { - Vector2 start = NPC.Center; - NPC.Center = endPoint; - AttackFlag = true; - NPC.netUpdate = true; - } - else - { - TeleportTime--; - if (TeleportTime < 0) - { - TeleportTime = 0; - Time = -1; - AttackFlag = false; - AttackCounter++; - - if (AttackCounter <= SanguineTeleportCount) - { - SoundStyle explosion = new("CalamityMod/Sounds/Custom/Ravager/RavagerMissileExplosion") - { - Volume = 0.5f - }; - SoundEngine.PlaySound(explosion, NPC.Center); - - for (int i = 0; i < SanguineScytheCount; i++) - { - float initalSpeed = 16f; - if (death && i % 2 == 0) - initalSpeed /= 2f; - - if (Main.netMode != NetmodeID.MultiplayerClient) - Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, Vector2.UnitX.RotatedBy(MathHelper.TwoPi / SanguineScytheCount * i) * initalSpeed, ModContent.ProjectileType(), BloodScytheDamage, 0.5f); - } - } - - Vector2 direction; - if (AttackCounter < SanguineTeleportCount) - { - direction = Main.rand.NextFloat(0f, MathHelper.TwoPi).ToRotationVector2(); - AttackPosition = target.Center + (direction * SanguineTeleportDistance); - } - else - { - direction = Vector2.UnitX * (Main.rand.NextBool() ? -1 : 1); - AttackPosition = target.Center + (direction * SanguineFinalTeleportOffset.X) + (Vector2.UnitY * -SanguineFinalTeleportOffset.Y); - } - - NPC.netUpdate = true; - - BoCAfterImages = []; - NPC.Opacity = 1f; - } - } - - NPC.Opacity = 1 - (TeleportTime / (TeleportDuration / 2f)); - } - #endregion - break; - case BrainAIState.CrimsonEyes: - #region Attack Start - if (Time <= 30) - { - if (Time >= 6 && Time <= 12) - { - if (Time == 6) - { - SoundEngine.PlaySound(Roar, NPC.Center); - - for (int i = 1; i <= 3; i++) - { - Color color = i switch - { - 1 => Color.Yellow, - 2 => Color.Orange, - _ => Color.Red, - }; - PulseRing ring = new(NPC.Center, NPC.velocity * 0.5f, color, 0f, 1f + i * 0.5f, 24); - GeneralParticleHandler.SpawnParticle(ring); - } - - CalamityUtils.AddScreenshakeAt(NPC.Center, 10f); - } - - for (int i = 0; i < 12; i++) - { - Point start = target.Center.ToTileCoordinates() + new Point(Main.rand.Next(-64, 65), 48); - for (int j = 0; j < 96; j++) - { - Point current = start - new Point(0, j); - if (!Main.tile[current].IsTileSolid() && Main.tile[current - new Point(0, 1)].IsTileSolid()) - Dust.NewDust(current.ToWorldCoordinates(0, 0), 16, 16, DustID.Crimstone, 0, 3); - } - } - } - } - #endregion - #region Attack - else - { - #region Eye Spawning - if (Time < CrimsonEyeAttackDuration && CalamityUtils.CountProjectiles(ModContent.ProjectileType()) < CrimsonEyeCap && Time % CrimsonEyeRate == 0) - { - Vector2 spawnPos = target.Center; - int i = 0; - for (i = 0; i <= 32; i++) - { - spawnPos = target.Center + Main.rand.NextVector2Circular(256, 256); - - if (Collision.IsWorldPointSolid(spawnPos)) - continue; - - bool alreadyFilled = false; - foreach (Projectile p in Main.ActiveProjectiles) - { - if (p.type != ModContent.ProjectileType()) - continue; - - Rectangle hitbox = new((int)spawnPos.X - 50, (int)spawnPos.Y - 18, 100, 36); - - if (p.Hitbox.Intersects(hitbox)) - { - alreadyFilled = true; - break; - } - } - - if (alreadyFilled) - continue; - - if (Collision.CanHitLine(spawnPos, 1, 1, target.position, target.width, target.height)) - break; - } - - if (i == 32) - spawnPos = target.Center; - - if (Main.netMode != NetmodeID.MultiplayerClient) - Projectile.NewProjectile(NPC.GetSource_FromThis(), spawnPos, Vector2.Zero, ModContent.ProjectileType(), CrimsonEyeDamage, 0f); - } - #endregion - - #region Early Movement - if (Time < 180) - { - float dist = 210; - - fromTarget = (NPC.Center - target.Center).SafeNormalize(Vector2.UnitX); - goalPos = target.Center + (fromTarget * dist) - (Vector2.UnitY * 32); - if (NPC.DistanceSQ(goalPos) <= 2048) - NPC.velocity *= 0.9f; - else if (NPC.velocity.LengthSquared() < 16f) //7.5^2 - NPC.velocity += NPC.DirectionTo(goalPos).SafeNormalize(Vector2.Zero) * 0.1f; - else - NPC.velocity = NPC.DirectionTo(goalPos).SafeNormalize(Vector2.Zero) * 4f; - } - #endregion - - #region Scythe Movement + Attack - else - { - if (Time < CrimsonEyeAttackIdleDuration) - NPC.velocity *= 0.9f; - if (Time >= CrimsonEyeAttackIdleDuration + CrimsonEyeAttackSetUpDuration && Time < CrimsonEyeAttackDuration) - { - if (Time == CrimsonEyeAttackIdleDuration + CrimsonEyeAttackSetUpDuration) - NPC.velocity = NPC.DirectionTo(target.Center); - - bool onSurface = target.Center.Y / 16f < Main.worldSurface; - speed = onSurface ? 10f : 8f; - if (Time < CrimsonEyeAttackIdleDuration + CrimsonEyeAttackSetUpDuration + CrimsonEyeAttackBuildUpDuration) - { - float lerp = CalamityUtils.SineInEasing((Time - (CrimsonEyeAttackIdleDuration + CrimsonEyeAttackSetUpDuration)) / CrimsonEyeAttackBuildUpDuration, 1); - speed = MathHelper.Lerp(0f, speed, lerp); - } - - float turnAmt = TurnAccelerationMultiplier * ((NPC.Distance(target.Center) - TurnAccelerationDistanceBuffer) / TurnAccelerationDistanceDivisor); - - NPC.velocity = NPC.velocity.RotateDirectionTowards(NPC.AngleTo(target.Center), turnAmt) * speed; - } - else - { - NPC.velocity *= 0.9f; - - if (Time == CrimsonEyeAttackDuration) - { - foreach (Projectile p in Main.ActiveProjectiles) - { - if (p.type != ModContent.ProjectileType()) - continue; - - p.timeLeft = 60; - } - } - - if (Time > CrimsonEyeAttackDuration + CrimsonEyeAttackEndDuration) - SetupForNextAttack(); - } - - if (Time == CrimsonEyeAttackIdleDuration) - { - SoundStyle explosion = new("CalamityMod/Sounds/Custom/Ravager/RavagerMissileExplosion"); - explosion.Volume = 0.5f; - - SoundEngine.PlaySound(explosion, NPC.Center); - if (Main.netMode != NetmodeID.MultiplayerClient) - { - float projCount = 10; - for (int i = 0; i < projCount; i++) - Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, Vector2.Zero, ModContent.ProjectileType(), BloodScytheDamage, 0.5f, -1, MathHelper.TwoPi / projCount * i); - } - } - } - #endregion - } - #endregion - break; - case BrainAIState.IllusionDash: - #region Attack Start - if (Time < IllusionDashTeleportDuration) - { - if (Time == 0) - { - AttackPosition = target.Center; - AttackRotation = Main.rand.NextFloat(0, MathHelper.TwoPi); - NPC.netUpdate = true; - } - - TeleportDuration = IllusionDashTeleportDuration; - - Vector2 endPoint = AttackPosition + (AttackRotation.ToRotationVector2() * IllusionDashTeleportDistance); - - if (Time < (TeleportDuration / 2f)) - { - if (Time % 4 == 0) - { - Vector2 startPoint = NPC.Center; - - for (int i = 0; i < (death ? 8 : 4); i++) - { - Vector2 myEndPoint = AttackPosition + ((AttackRotation + (death ? MathHelper.PiOver4 : MathHelper.PiOver2) * i).ToRotationVector2() * IllusionDashTeleportDistance); - Vector2 direction = myEndPoint - startPoint; - - float curveIntensity = Main.rand.NextFloat(-0.2f, 0.2f); - Vector2 perpindicular = direction.RotatedBy(MathHelper.PiOver2); - - Vector2 controlPoint1 = startPoint + (direction * 0.25f) + (perpindicular * curveIntensity); - Vector2 controlPoint2 = startPoint + (direction * 0.75f) + (perpindicular * curveIntensity); - - BezierCurve path = new BezierCurve(startPoint, controlPoint1, controlPoint2, myEndPoint); - - BrainofCthulhuAfterImage afterimage = new(path, NPC.rotation, Vector2.One, (int)((TeleportDuration * 0.75f) - Time), BoCFrame); - BoCAfterImages.Add(afterimage); - GeneralParticleHandler.SpawnParticle(afterimage); - } - } - TeleportTime++; - } - else if (Time == (TeleportDuration / 2f) && !AttackFlag) - { - AttackFlag = true; - - for (int i = 0; i < (death ? 8 : 4); i++) - { - float rot = AttackRotation + (death ? MathHelper.PiOver4 : MathHelper.PiOver2) * i; - Vector2 spawnPos = AttackPosition + (rot.ToRotationVector2() * IllusionDashTeleportDistance); - if (i == 0) - NPC.Center = spawnPos; - else if (Main.netMode != NetmodeID.MultiplayerClient) - NPC.NewNPCDirect(NPC.GetSource_FromThis(), spawnPos, ModContent.NPCType(), 0, 15, 30, rot).netUpdate = true; - } - - NPC.netUpdate = true; - } - else - TeleportTime--; - - NPC.Opacity = 1 - (TeleportTime / (TeleportDuration / 2f)); - } - #endregion - else - { - float startTime = Time - IllusionDashTeleportDuration; - - if (startTime == 0) - { - AttackPosition = NPC.Center; - TeleportTime = 0; - AttackFlag = false; - - BoCAfterImages = []; - NPC.Opacity = 1f; - - GenericSparkle sparkle = new(NPC.Center, Vector2.Zero, Color.Yellow, Color.Orange, 2f, 12, needed: true); - GeneralParticleHandler.SpawnParticle(sparkle); - - NPC.netUpdate = true; - - foreach (NPC n in Main.ActiveNPCs) - if (n.type == ModContent.NPCType()) - n.netUpdate = true; - } - if (startTime < 30) - { - float lerp = startTime / 30f; - 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)); - } - else if (startTime <= 30 + IllusionDashSpinDuration) - { - NPC.Center = target.Center + AttackRotation.ToRotationVector2() * IllusionDashCloseInDistance; - - AttackRotation += MathHelper.Lerp(IllusionDashStartingSpinSpeed, 0f, CalamityUtils.SineOutEasing((startTime - 30) / (float)IllusionDashSpinDuration, 1)); - } - else if (startTime < 30 + IllusionDashSpinDuration + 30) - { - float reelBackSpeedExponent = 2.6f; - float reelBackCompletion = Utils.GetLerpValue(0f, 30, startTime - 130, true); - float reelBackSpeed = MathHelper.Lerp(2.5f, 16f, MathF.Pow(reelBackCompletion, reelBackSpeedExponent)); - Vector2 reelBackVelocity = (AttackRotation + MathHelper.Pi).ToRotationVector2() * -reelBackSpeed; - NPC.velocity = Vector2.Lerp(NPC.velocity, reelBackVelocity, 0.25f); - } - else if (startTime <= 30 + IllusionDashSpinDuration + 30 + IllusionDashFakeoutTeleportDuration) //176 - { - NPC.velocity = Vector2.Zero; - - if (startTime == 30 + IllusionDashSpinDuration + 30) - { - AttackPosition = target.Center; - AttackRotation = AttackRotation + MathHelper.Pi + Main.rand.NextFloat(-MathHelper.PiOver2, MathHelper.PiOver2); - NPC.netUpdate = true; - } - - wrappedCounter = startTime - (30 + IllusionDashSpinDuration + 30); - - TeleportDuration = IllusionDashFakeoutTeleportDuration; - - Vector2 endPoint = AttackPosition + (AttackRotation.ToRotationVector2() * 270); - - if (wrappedCounter < (TeleportDuration / 2f)) - { - if (wrappedCounter % 2 == 0) - { - Vector2 startPoint = NPC.Center; - - Vector2 direction = endPoint - startPoint; - - float curveIntensity = Main.rand.NextFloat(-0.2f, 0.2f); - Vector2 perpindicular = direction.RotatedBy(MathHelper.PiOver2); - - Vector2 controlPoint1 = startPoint + (direction * 0.25f) + (perpindicular * curveIntensity); - Vector2 controlPoint2 = startPoint + (direction * 0.75f) + (perpindicular * curveIntensity); - - BezierCurve path = new BezierCurve(startPoint, controlPoint1, controlPoint2, endPoint); - - BrainofCthulhuAfterImage afterimage = new(path, NPC.rotation, Vector2.One, (int)((TeleportDuration * 0.75f) - wrappedCounter), BoCFrame); - BoCAfterImages.Add(afterimage); - GeneralParticleHandler.SpawnParticle(afterimage); - } - TeleportTime++; - } - else if (wrappedCounter == (int)(TeleportDuration / 2f) && !AttackFlag) - { - AttackFlag = true; - NPC.Center = endPoint; - } - else - { - TeleportTime--; - if (TeleportTime <= 0) - { - TeleportTime = 0; - BoCAfterImages = []; - ResetAttackValues(); - NPC.Opacity = 1f; - NPC.netUpdate = true; - AttackRotation = NPC.AngleTo(target.Center); - } - } - - NPC.Opacity = 1 - (TeleportTime / (TeleportDuration / 2f)); - } - else if (startTime < 90 + IllusionDashSpinDuration + 30 + IllusionDashFakeoutTeleportDuration + 30) - { - NPC.velocity *= 0.9f; - if(startTime % 15 == 0) - { - for (int i = 0; i < 2; i++) - { - dir = NPC.DirectionTo(target.Center); - if (Main.netMode != NetmodeID.MultiplayerClient) - { - Vector2 initialDir = dir.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 4f, MathHelper.Pi / 4f)); - Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, initialDir * Main.rand.NextFloat(10f, 25f), ProjectileID.BloodNautilusShot, BloodShotDamage, 0.5f, ai0: dir.ToRotation() + MathHelper.TwoPi, ai1: initialDir.ToRotation()); - } - NPC.velocity -= dir * 2f; - } - } - } - else if(startTime >= 135 + IllusionDashSpinDuration + 30 + IllusionDashFakeoutTeleportDuration + 30) - { - foreach (NPC n in Main.ActiveNPCs) - if (n.type == ModContent.NPCType()) - n.active = false; - - SetupForNextAttack(); - } - } - - - break; - case BrainAIState.IllusionTrick: - if (Time >= 90) - { - if (Time == 90) - { - foreach(Projectile p in Main.ActiveProjectiles) - { - if (!p.friendly) - continue; - - p.Calamity().IgnoreBoCIllusions = true; - } - - int brainAngleSlot = Main.rand.Next(0, IllusionTrickAngleGroups); - int brainDistSlot = Main.rand.Next(0, IllusionTrickGroupSize); - - if (Main.netMode != NetmodeID.MultiplayerClient) - for (int a = 0; a < IllusionTrickAngleGroups; a++) - for (int d = 0; d < IllusionTrickGroupSize; d++) - { - if (a != brainAngleSlot || d != brainDistSlot) - NPC.NewNPC(NPC.GetSource_FromThis(), 0, 0, ModContent.NPCType(), 0, MathHelper.TwoPi / IllusionTrickAngleGroups * a, FalseBrain.TimeDivisor / IllusionTrickGroupSize * d); - } - - AttackTime = (int)(FalseBrain.TimeDivisor / IllusionTrickGroupSize * brainDistSlot); - AttackRotation = MathHelper.TwoPi / IllusionTrickAngleGroups * brainAngleSlot; - AttackFlag = false; - AttackPosition = target.Center; - - NPC.ShowNameOnHover = false; - NPC.netUpdate = true; - } - - NPC.damage = 0; - - if (AttackFlag) - { - 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 - NPC.velocity *= 0.95f; - - if (AttackCounter >= IllusionTrickStunDuration) - { - NPC.damage = NPC.defDamage; - SetupForNextAttack(); - NPC.Opacity = 1f; - TeleportTime = 0; - break; - } - - AttackCounter++; - } - else if(Time >= IllusionTrickTimeLimit) //Players have failed to find the real BoC within the time limit - { - if (Time == IllusionTrickTimeLimit) - { - foreach (Player p in Main.ActivePlayers) - { - if (p.Distance(NPC.Center) > DespawnRange) - continue; - - AttackList.Add(p.whoAmI); - } - - foreach (NPC n in Main.ActiveNPCs) - { - if (n.type != ModContent.NPCType()) - continue; - - n.ModNPC().BeenHit = true; - } - - for (int i = 1; i <= 3; i++) - { - Color color = i switch - { - 1 => Color.Yellow, - 2 => Color.Orange, - _ => Color.Red, - }; - PulseRing ring = new(NPC.Center, NPC.velocity * 0.5f, color, 0f, 1f + i * 0.5f, 24); - GeneralParticleHandler.SpawnParticle(ring); - } - } - else if(Time % 30 == 0) - { - if (AttackList.Count > 0) - { - if (Main.netMode != NetmodeID.MultiplayerClient) - Projectile.NewProjectile(NPC.GetSource_FromThis(), NPC.Center, Vector2.Zero, ModContent.ProjectileType(), 0, 0f, -1, AttackList[0], 2f); - AttackList.RemoveAt(0); - } - else - { - Vector2 direction = target.velocity.SafeNormalize(Vector2.UnitX * target.direction).RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 3f, MathHelper.Pi / 3f)); - float distance = DefaultTeleportDistance; - AttackPosition = target.Center + (direction * distance); - BoCAfterImages = []; - NPC.Opacity = 1f; - TeleportTime = 0; - Time = ChaseTime - 1; - NPC.damage = NPC.defDamage; - NPC.netUpdate = true; - ResetAttackValues(); - - AIState = BrainAIState.Phase2Idle; - } - } - } - else - { - CachedRatio = (float)Math.Cos(AttackTime * MathHelper.TwoPi / FalseBrain.TimeDivisor); - - float lerp = CalamityUtils.SineInOutEasing(MathHelper.Clamp((Time - 150) / 30f, 0f, 1f), 1); - float baseDist = 240; - float circleDist = 480; - if (Time - 150 < 30f) - { - baseDist = MathHelper.Lerp(480, 240, lerp); - circleDist = MathHelper.Lerp(240, 480, lerp); - } - 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; - AttackCounter = 0; - } - } - else if (Time <= 60) - { - TeleportDuration = 60; - TeleportTime++; - NPC.Opacity = 1 - (Time / 60f); - - if (Time < 50) - { - Vector2 startPoint = NPC.Center; - Vector2 endPoint = NPC.Center + Vector2.UnitX.RotatedBy(Main.rand.NextFloat(0, MathHelper.TwoPi)) * Main.rand.NextFloat(240, 480); - - Vector2 direction = endPoint - startPoint; - float curveIntensity = Main.rand.NextFloat(-0.2f, 0.2f); - Vector2 perpindicular = direction.RotatedBy(MathHelper.PiOver2); - - Vector2 controlPoint1 = startPoint + (direction * 0.25f) + (perpindicular * curveIntensity); - Vector2 controlPoint2 = startPoint + (direction * 0.75f) + (perpindicular * curveIntensity); - - BezierCurve path = new BezierCurve(startPoint, controlPoint1, controlPoint2, endPoint); - - BrainofCthulhuAfterImage afterimage = new(path, NPC.rotation, Vector2.One, (int)(60 - Time), BoCFrame); - BoCAfterImages.Add(afterimage); - GeneralParticleHandler.SpawnParticle(afterimage); - } - } - else - { - NPC.Opacity = 0f; - BoCAfterImages = []; - } - - if (Time >= 180) - AttackTime++; - else if (Time >= 150) - AttackTime += (Time - 150) / 30f; - break; - #endregion - - case BrainAIState.DeathAnimation: - if (Time == 0) - NPC.velocity = NPC.DirectionFrom(target.Center) * 6f; - else - NPC.velocity *= 0.95f; - - NPC.rotation = MathHelper.Pi / 24f * NPC.oldVelocity.X; - TeleportTime *= 0.6f; - if (TeleportTime < 0.005f) - TeleportTime = 0; - BoCDrawOffset *= 0.6f; - NPC.Opacity = BringOpacityTo(NPC.Opacity, 1, 0.1f); - - (float angle, Vector2 offset, int time)[] bloodGushingData = [ - (MathHelper.Pi / 6f, new(18, 12), 90), - (MathHelper.Pi, new(-30, -10), 150), - (-MathHelper.Pi / 4f, new(20, -40), 180), - (MathHelper.Pi + MathHelper.Pi / 4f, new(-20, -40), 200), - (MathHelper.Pi / 1.75f, new(-5, 22), 210) - ]; - - for (int i = 0; i < bloodGushingData.Length; i++) - { - if (Time >= bloodGushingData[i].time) - { - if (Time == bloodGushingData[i].time) - { - Vector2 bloodDir = bloodGushingData[i].angle.ToRotationVector2(); - BloodParticle2 p2 = new(NPC.Center + bloodGushingData[i].offset.RotatedBy(NPC.rotation), bloodDir * 7.5f, 16, 0.5f, Color.Red); - GeneralParticleHandler.SpawnParticle(p2); - NPC.velocity = bloodDir * -4f; - - SoundStyle explosion = new("CalamityMod/Sounds/Custom/Ravager/RavagerMissileExplosion") - { - Volume = 0.5f, - Pitch = i / (float)(bloodGushingData.Length - 1) - }; - SoundEngine.PlaySound(explosion, NPC.Center); - - Main.LocalPlayer.SetScreenshake(1f); - } - - for (int j = 0; j < 2; j++) - { - BloodParticle p = new(NPC.Center + bloodGushingData[i].offset.RotatedBy(NPC.rotation), (bloodGushingData[i].angle + Main.rand.NextFloat(-MathHelper.Pi / 10f, MathHelper.Pi / 10f)).ToRotationVector2() * Main.rand.NextFloat(5f, 10f), 32, 1f, Color.Red); - GeneralParticleHandler.SpawnParticle(p); - } - } - - } - - if (Time >= 215) - { - SoundStyle explosion = new("CalamityMod/Sounds/Custom/Ravager/RavagerMissileExplosion"); - SoundEngine.PlaySound(explosion, NPC.Center); - - Main.LocalPlayer.SetScreenshake(2f); - - int pCount = 10; - for (int i = 0; i < pCount; i++) - { - float initalSpeed = 24f; - Vector2 pVelo = Vector2.UnitX.RotatedBy(MathHelper.TwoPi / pCount * i) * initalSpeed; - - for (int j = 0; j < 2; j++) - { - BloodParticle p = new(NPC.Center, pVelo.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 6f, MathHelper.Pi / 6f)) * Main.rand.NextFloat(0.5f, 1f), 32, 1f, Color.Red); - GeneralParticleHandler.SpawnParticle(p); - } - BloodParticle2 p2 = new(NPC.Center, pVelo * 0.75f, 16, 0.5f, Color.Red); - GeneralParticleHandler.SpawnParticle(p2); - } - - NPC.dontTakeDamage = false; - if(Main.netMode != NetmodeID.MultiplayerClient) - NPC.StrikeInstantKill(); - } - - float animationCompletion = Time / 215f; - NPC.frameCounter += 2 * animationCompletion; - - if (Main.rand.NextFloat(0.5f, 1f) < animationCompletion) - { - Vector2 edgeBloodDir = Main.rand.NextVector2CircularEdge(1, 1); - BloodParticle b = new(NPC.Center + (edgeBloodDir * NPC.Size * 0.75f), edgeBloodDir.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 10f, MathHelper.Pi / 10f)) * Main.rand.NextFloat(2f, 4f), 16, 0.75f, Color.Red); - GeneralParticleHandler.SpawnParticle(b); - } - break; - } - - #region Projectile Altering - foreach (Projectile p in Main.ActiveProjectiles) - { - if (p.type != ProjectileID.BloodNautilusShot || p.ai[0] == 0) - continue; - - int startUpTime = 20; - float speedUpTime = 30; - float slowDownMult = 0.96f; - float speedUpMult = 1.025f; - if(AIState == BrainAIState.IllusionDash) - { - startUpTime = 20; - speedUpTime = 30; - slowDownMult = 0.96f; - speedUpMult = 1.025f; - } - - if (p.ai[2] <= startUpTime) - p.velocity *= slowDownMult; - else - { - p.velocity *= speedUpMult; - if (p.ai[2] <= startUpTime + speedUpTime) - { - float newAngle = p.ai[1].AngleLerp(p.ai[0] - MathHelper.TwoPi, (p.ai[2] - startUpTime) / speedUpTime); - - p.velocity = newAngle.ToRotationVector2() * p.velocity.Length(); - } - } - p.ai[2]++; - } - #endregion - - NPC.oldVelocity = NPC.velocity; - Time++; - - return false; - } - - public override void SendExtraAI(BitWriter bitWriter, BinaryWriter binaryWriter) - { - binaryWriter.Write((int)PreviousAttack); - - binaryWriter.Write(TeleportTime); - binaryWriter.Write(TeleportDuration); - - binaryWriter.Write(SpawnTime); - binaryWriter.Write(SpawnDelay); - - binaryWriter.Write(CachedRatio); - - binaryWriter.WriteFlags(OnSecondCreeperPhase, isNegative, AttackFlag); - - binaryWriter.Write(AttackRotation); - binaryWriter.Write(AttackTime); - binaryWriter.Write(AttackCounter); - - binaryWriter.WritePackedVector2(AttackPosition); - - binaryWriter.Write(availableAttacks.Count); - for (int i = 0; i < availableAttacks.Count; i++) - binaryWriter.Write((int)availableAttacks[i]); - - binaryWriter.Write(AttackList.Count); - for (int i = 0; i < AttackList.Count; i++) - binaryWriter.Write(AttackList[i]); - } - - public override void ReceiveExtraAI(BitReader bitReader, BinaryReader binaryReader) - { - PreviousAttack = (BrainAIState)binaryReader.ReadInt32(); - - TeleportTime = binaryReader.ReadSingle(); - TeleportDuration = binaryReader.ReadSingle(); - - SpawnTime = binaryReader.ReadSingle(); - SpawnDelay = binaryReader.ReadInt32(); - - CachedRatio = binaryReader.ReadSingle(); - - binaryReader.ReadFlags(out OnSecondCreeperPhase, out isNegative, out AttackFlag); - - AttackRotation = binaryReader.ReadSingle(); - AttackTime = binaryReader.ReadSingle(); - AttackCounter = binaryReader.ReadInt32(); - - AttackPosition = binaryReader.ReadPackedVector2(); - - int availableLength = binaryReader.ReadInt32(); - availableAttacks.Clear(); - for (int i = 0; i < availableLength; i++) - availableAttacks.Add((BrainAIState)binaryReader.ReadInt32()); - - int attackLength = binaryReader.ReadInt32(); - AttackList.Clear(); - for (int i = 0; i < attackLength; i++) - AttackList.Add(binaryReader.ReadSingle()); - } - - public override bool? CanBeHitByProjectile(Mod mod, Projectile projectile) - { - if (AIState == BrainAIState.IllusionTrick && !AttackFlag && projectile.Calamity().IgnoreBoCIllusions) - return false; - return base.CanBeHitByProjectile(mod, projectile); - } - - public override void ModifyHitByItem(Mod mod, Player player, Item item, ref NPC.HitModifiers modifiers) - { - if (AIState != BrainAIState.DeathAnimation) - modifiers.SetMaxDamage(NPC.life - 1); - } - - public override void ModifyHitByProjectile(Mod mod, Projectile projectile, ref NPC.HitModifiers modifiers) - { - if (AIState != BrainAIState.DeathAnimation) - modifiers.SetMaxDamage(NPC.life - 1); - } - - public override void HitEffect(Mod mod, NPC.HitInfo hit) - { - if (AIState != BrainAIState.DeathAnimation && (NPC.life + 1) <= hit.Damage) - { - NPC.life = 1; - NPC.BossBar = null; - NPC.dontTakeDamage = true; - - if (AIState == BrainAIState.Stunned) - TeleportTime = 0; - - AIState = BrainAIState.DeathAnimation; - ResetAttackValues(); - Time = 0; - return; - } - - if (AIState == BrainAIState.IllusionTrick && Time < 960) - AttackFlag = true; - } - - public override bool PreKill(Mod mod) - { - return AIState == BrainAIState.DeathAnimation && !NPC.dontTakeDamage; - } - - public override void FindFrame(Mod mod, int frameHeight) - { - if (BoCFrame == Rectangle.Empty) - BoCFrame = TextureAssets.Npc[NPCID.BrainofCthulhu].Frame(verticalFrames: 8); - - if (NPC.frameCounter == 0) - BoCFrame.Y += frameHeight; - - if (AIState <= BrainAIState.Phase2TransitionClosed) - { - if (BoCFrame.Y > frameHeight * 3) - BoCFrame.Y = 0; - return; - } - if (BoCFrame.Y < frameHeight * 4) - BoCFrame.Y = frameHeight * 4; - - if (BoCFrame.Y > frameHeight * 7) - BoCFrame.Y = frameHeight * 4; - } - - public override bool PreDraw(Mod mod, SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) - { - bool phase1 = AIState < BrainAIState.Phase2TransitionClosed; - bool drawBrain = true; - - if (phase1) - { - List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper).ToList(); - creepers.Sort((a, b) => b.DistanceSQ(NPC.Center).CompareTo(a.DistanceSQ(NPC.Center))); - - int c = 0; - foreach (NPC creeper in creepers) - { - List curvePoints = RevBoCSystem.VerletTendrils[creeper.AIOverride().CreeperID]; - if (curvePoints is null) - continue; - - float glowIntensity = creeper.AIOverride().ConnectionOpacity; - Color ichorLess = Color.Lerp(Color.Transparent, Color.OrangeRed * 0.333f, glowIntensity); - Color ichorful = Color.Lerp(Color.OrangeRed * 0.25f, Color.Orange * 0.666f, glowIntensity); - - for (int i = 0; i < curvePoints.Count; i++) - { - Vector2 start = curvePoints[i].position; - Vector2 end = i == curvePoints.Count - 1 ? creeper.Center : curvePoints[i + 1].position; - Vector2 center = (end + start) / 2f; - start -= Main.screenPosition; - end -= Main.screenPosition; - - float rotation = (end - start).ToRotation() - MathHelper.PiOver2; - - float flowTime = creeper.AIOverride().FlowTime; - float flowAmt = creeper.AIOverride().FlowAmount; - float ichorRatio = CalamityUtils.ExpInEasing((float)Math.Sin((flowTime + (i * flowAmt)) * 2f) / 2f + 0.5f, 1); - - Color glowColor = Color.Lerp(ichorLess, ichorful, ichorRatio); - - float dist = Vector2.Distance(start, end); - Vector2 tendrilScale = new(1f + (0.5f * (ichorRatio * (1 + (glowIntensity * 0.5f)))), dist / RevBoCSystem.tendril.Height()); - - spriteBatch.Draw(RevBoCSystem.tendril.Value, start, null, Lighting.GetColor(center.ToTileCoordinates()) * NPC.Opacity, rotation, RevBoCSystem.tendril.Size() * Vector2.UnitX * 0.5f, tendrilScale, SpriteEffects.None, 0f); - spriteBatch.Draw(RevBoCSystem.GetTendrilGlow(), start, null, glowColor * NPC.Opacity, rotation, RevBoCSystem.GetTendrilGlow().Size() * Vector2.UnitX * 0.5f, tendrilScale, SpriteEffects.None, 0f); - } - - c++; - } - - foreach (NPC creeper in creepers) - { - float glowIntensity = creeper.AIOverride().ConnectionOpacity; - - spriteBatch.Draw(RevBoCSystem.GetCreeperGlow(), creeper.Center - Main.screenPosition, null, Color.Orange * glowIntensity, creeper.rotation, TextureAssets.Npc[NPCID.Creeper].Size() * 0.5f, creeper.scale * 1.15f, 0, 0); - - spriteBatch.Draw(TextureAssets.Npc[NPCID.Creeper].Value, creeper.Center - Main.screenPosition, null, Lighting.GetColor(creeper.Center.ToTileCoordinates()).MultiplyRGB(Color.Lerp(Color.White, new Color(255, 180, 180), glowIntensity)), creeper.rotation, TextureAssets.Npc[NPCID.Creeper].Size() * 0.5f, creeper.scale, 0, 0); - } - } - else - { - List falseBrains = Main.npc.Where(n => n.active && n.type == ModContent.NPCType()).ToList(); - if (falseBrains.Count > 0) - { - drawBrain = false; - - falseBrains.Add(NPC); - falseBrains.Sort((a, b) => - { - float aValue; - float bValue; - - if (a.ModNPC is FalseBrain falseA) - aValue = falseA.DrawPriority; - else - aValue = a.AIOverride().CachedRatio; - - if (b.ModNPC is FalseBrain falseB) - bValue = falseB.DrawPriority; - else - bValue = b.AIOverride().CachedRatio; - - return aValue.CompareTo(bValue); - }); - - foreach (NPC n in falseBrains) - { - if (n.ModNPC is FalseBrain falseBrain) - falseBrain.DrawSelf(spriteBatch, screenPos, Lighting.GetColor(n.Center.ToTileCoordinates())); - else - DrawBrainLikeFakes(spriteBatch, n); - } - } - } - - if (drawBrain) - DrawBrain(spriteBatch, NPC); - - return false; - } - - private static void DrawBrain(SpriteBatch spriteBatch, NPC brain) - { - BrainOfCthulhuAI ai = brain.AIOverride(); - bool phase1 = ai.AIState < BrainAIState.Phase2TransitionClosed; - - Vector2 drawPos = brain.Center + ai.BoCDrawOffset + (Vector2.UnitY * 16) - Main.screenPosition; - Vector2 scale = Vector2.One; - - if (!phase1 && ai.TeleportTime != 0) - { - ai.BoCAfterImages.RemoveAll(p => p.Time > p.Lifetime); - foreach (Particle p in ai.BoCAfterImages) - p.CustomDraw(spriteBatch); - - //Color glowColor = Color.White * (teleportCounter / 30f); - scale = Vector2.Lerp(Vector2.One, new Vector2(0.5f + ((float)Math.Cos(ai.Time / (ai.TeleportDuration / 2f) * MathHelper.TwoPi) / 2f + 0.5f), 0.5f + ((float)Math.Sin(ai.Time / (ai.TeleportDuration / 2f) * MathHelper.TwoPi) / 2f + 0.5f)), CalamityUtils.SineInOutEasing(ai.TeleportTime / (ai.TeleportDuration / 2f), 1)); - - spriteBatch.Draw(TextureAssets.Npc[NPCID.BrainofCthulhu].Value, drawPos, ai.BoCFrame, Lighting.GetColor(brain.Center.ToTileCoordinates()) * brain.Opacity, brain.rotation, ai.BoCFrame.Size() * 0.5f, scale * brain.scale, 0, 0); - //spriteBatch.Draw(GetBrainGlow(), drawPos, NPC.frame, glowColor, NPC.rotation, NPC.frame.Size() * 0.5f, scale, 0, 0); - } - else - spriteBatch.Draw(TextureAssets.Npc[NPCID.BrainofCthulhu].Value, drawPos, ai.BoCFrame, Lighting.GetColor(brain.Center.ToTileCoordinates()) * brain.Opacity, brain.rotation, ai.BoCFrame.Size() * 0.5f, scale * brain.scale, 0, 0); - } - - private static void DrawBrainLikeFakes(SpriteBatch spriteBatch, NPC brain) - { - BrainOfCthulhuAI ai = brain.AIOverride(); - - Vector2 scaleDistort = new Vector2((float)Math.Cos(Main.GlobalTimeWrappedHourly * MathHelper.TwoPi * 2) / 2f, (float)Math.Sin(Main.GlobalTimeWrappedHourly * MathHelper.TwoPi * 2) / 2f); - - int spawnTime = 150 - ((int)ai.Time); - float startLerp = spawnTime / 60f; - - Color drawColor = Lighting.GetColor(brain.Center.ToTileCoordinates()); - - if (spawnTime > 0) - { - drawColor *= (1 - startLerp); - scaleDistort *= startLerp; - } - else - scaleDistort = Vector2.Zero; - - spriteBatch.Draw(TextureAssets.Npc[NPCID.BrainofCthulhu].Value, brain.Center + (Vector2.UnitY * 16) - Main.screenPosition, ai.BoCFrame, drawColor, brain.rotation, ai.BoCFrame.Size() * 0.5f, (Vector2.One + scaleDistort) * brain.scale, 0, 0); - } - - private void SetupForNextAttack() - { - Player target = Main.player[NPC.target]; - - Vector2 direction = target.velocity.SafeNormalize(Vector2.UnitX * target.direction).RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 3f, MathHelper.Pi / 3f)); - float distance = DefaultTeleportDistance; - AttackPosition = target.Center + (direction * distance); - BoCAfterImages = []; - Time = ChaseTime - 1; - ResetAttackValues(); - NPC.netUpdate = true; - - if (availableAttacks.Count != 0) - { - if (availableAttacks[0] != BrainAIState.Phase2Idle) - AttackCounter = 4; - else - availableAttacks.RemoveAt(0); - } - - AIState = BrainAIState.Phase2Idle; - } - - private void ResetAttackValues() - { - isNegative = false; - AttackRotation = 0; - AttackTime = 0; - AttackFlag = false; - AttackPosition = Vector2.Zero; - AttackCounter = 0; - } - - public static int GetBrainOfCthuluCreepersCountRevDeath() => CalamityWorld.death ? 30 : 21; - - private static float BringOpacityTo(float currentOpacity, float goalOpacity, float changeAmount = 0.025f) - { - if (currentOpacity == goalOpacity) - return goalOpacity; - - if (currentOpacity < goalOpacity) - { - currentOpacity += changeAmount; - if (currentOpacity >= goalOpacity) - return goalOpacity; - else - return currentOpacity; - } - else - { - currentOpacity -= changeAmount; - if (currentOpacity <= goalOpacity) - return goalOpacity; - else - return currentOpacity; - } - } - - public class CreeperAI : VanillaAIOverride - { - internal float FlowTime = 0; - internal float FlowAmount => MathHelper.Lerp(0.1f, 0.15f, NPC.localAI[3]); - - internal enum CreeperAIState - { - Idle, - Charge - } - - internal int CreeperID { get => (int)NPC.ai[0]; set => NPC.ai[0] = value; } - internal CreeperAIState AIState { get => (CreeperAIState)NPC.ai[1]; set => NPC.ai[1] = (float)value; } - internal int Time = -1; - internal ref float AttackAngle => ref NPC.ai[2]; - internal ref float CachedValue1 => ref NPC.ai[3]; - internal int CachedValue2 = 0; - internal int PartnerIndex = -1; - internal Vector2 AttackPosition = Vector2.Zero; - internal float ConnectionOpacity = 0f; - - public override bool AI(Mod mod) - { - #region Despawn - if (NPC.crimsonBoss < 0) - { - NPC.active = false; - NPC.netUpdate = true; - return false; - } - #endregion - - #region Targetting - if (NPC.target < 0 || NPC.target == Main.maxPlayers || Main.player[NPC.target].dead || !Main.player[NPC.target].active) - CalamityUtils.CalamityTargeting(NPC, default); - #endregion - - #region Creeper Count Variables - int creeperCount = NPC.CountNPCS(NPC.type); - if (creeperCount > GetBrainOfCthuluCreepersCountRevDeath()) - creeperCount = GetBrainOfCthuluCreepersCountRevDeath(); - int localCreeperID = Main.npc.Where(n => n.active && n.type == NPCID.Creeper).ToList().IndexOf(NPC); - float CreeperAmountRatio = creeperCount / (float)GetBrainOfCthuluCreepersCountRevDeath(); - #endregion - - NPC brain = Main.npc[NPC.crimsonBoss]; - BrainOfCthulhuAI bocAI = brain.AIOverride(); - - bool death = CalamityWorld.death || BossRushEvent.BossRushActive; - - float bossCounter = bocAI.Time; - - bool evenID = CreeperID % 2 == 0; - - if (bocAI.AIState < 0) - NPC.damage = 0; - - List bossAIStatesToUse = [ - BrainAIState.UndergroundSpawnAnimation, - BrainAIState.SurfaceSpawnAnimation, - BrainAIState.Stunned, - BrainAIState.CreeperSwipes, - BrainAIState.CreeperCrush, - BrainAIState.CreeperOrbit, - BrainAIState.CreeperSpiral, - BrainAIState.DesperateOnslaught - ]; - bool useBossAIState = bossAIStatesToUse.Contains(bocAI.AIState) && bossCounter >= 0; - - if (bocAI.AIState == BrainAIState.UndergroundSpawnAnimation || bocAI.AIState == BrainAIState.SurfaceSpawnAnimation) - NPC.dontTakeDamage = true; - else - NPC.dontTakeDamage = false; - - if (useBossAIState) - switch (bocAI.AIState) - { - case BrainAIState.UndergroundSpawnAnimation: - case BrainAIState.SurfaceSpawnAnimation: - float baseRotation = MathHelper.TwoPi / (GetBrainOfCthuluCreepersCountRevDeath() / 2f) * (CreeperID / 2f); - Vector2 goalLocation; - float speedCap = 8f; - float accel = 1f; - float acceptableDist = 9216; - Player player = Main.player[NPC.target]; - - if (bocAI.SpawnTime != 0 && Time >= 0) //Brain has appeared - { - float brainTime = bossCounter - Math.Abs(bocAI.SpawnTime); - - if (brainTime < 180) - { - Vector2 baseOffset = new Vector2(evenID ? -360 : 360, 0); - Vector2 rotationOffset = Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 120f * (evenID ? -1 : 1))) * 128; - goalLocation = player.Center + baseOffset + rotationOffset; - } - else if (brainTime < 240) - { - Vector2 baseOffset = new Vector2(evenID ? -200 : 200, 64); - Vector2 rotationOffset = Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 60f * (evenID ? -1 : 1))) * 32; - goalLocation = brain.Center + baseOffset + rotationOffset; - speedCap = 12; - accel = 2f; - acceptableDist = 4096; - } - else - { - Vector2 baseOffset = new Vector2(evenID ? -360 : 360, -64); - Vector2 rotationOffset = Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 60f * (evenID ? -1 : 1))) * 128; - goalLocation = brain.Center + baseOffset + rotationOffset; - speedCap = 12; - accel = 2f; - acceptableDist = 4096; - } - Time++; - } - else - { - if (Time >= 0) //Has been brought down - { - Vector2 baseOffset = new Vector2(evenID ? -360 : 360, 0); - Vector2 rotationOffset = Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 120f * (evenID ? -1 : 1))) * 128; - goalLocation = player.Center + baseOffset + rotationOffset; - Time++; - } - else //Hasnt been brought down - { - Vector2 baseOffset = new Vector2(evenID ? -256 : 256, 0); - Vector2 rotationOffset = Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 120f * (evenID ? -1 : 1))) * 64; - goalLocation = brain.Center + baseOffset + rotationOffset; - } - } - - if (NPC.DistanceSQ(goalLocation) > acceptableDist) - { - NPC.velocity += NPC.DirectionTo(goalLocation) * accel; - NPC.velocity = NPC.velocity.ClampMagnitude(0f, speedCap); - } - - break; - case BrainAIState.DesperateOnslaught: - 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) - { - goalLocation = brain.Center + AttackPosition; - - if(WorldGen.SolidOrSlopedTile(goalLocation.ToTileCoordinates().X, goalLocation.ToTileCoordinates().Y)) - { - float rayDist = CalamityUtils.PreciseDistanceToTileCollisionHit(brain.Center, AttackAngle, 800, 4); - AttackPosition = (AttackAngle.ToRotationVector2() * (rayDist - 64)); - goalLocation = brain.Center + AttackPosition; - } - - if (NPC.DistanceSQ(goalLocation) > 4096) - { - NPC.velocity += NPC.DirectionTo(goalLocation); - NPC.velocity = NPC.velocity.ClampMagnitude(0f, 10f); - } - else - NPC.velocity *= 0.8f; - ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f); - NPC.damage = 0; - } - else - useBossAIState = false; - - Time++; - break; - case BrainAIState.Stunned: - NPC.velocity *= 0.9f; - NPC.damage = 0; - break; - case BrainAIState.CreeperSwipes: - if (bossCounter < 15) - { - useBossAIState = false; - Time = -1; - AIState = CreeperAIState.Idle; - break; - } - - if (brain.AIOverride().AttackList.Contains(NPC.whoAmI)) - { - if (Time < 0) - Time = 0; - } - else - { - if (Time >= 0) - Time = -1; - } - - baseRotation = MathHelper.TwoPi / (GetBrainOfCthuluCreepersCountRevDeath() / 2f) * (CreeperID / 2f); - bool singleHand = bocAI.AttackFlag; - int handSide = bocAI.AttackSign; - - if (Time == -1) - { - NPC.damage = 0; - NPC.knockBackResist = 0.72f; - - ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0f); - - if (!singleHand) - goalLocation = brain.Center + (Vector2.UnitY * -32f) + (Vector2.UnitX * (evenID ? -256 : 256)) + (Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 30f * (evenID ? -1 : 1))) * new Vector2(32, 96)); - else - goalLocation = brain.Center + (Vector2.UnitY * -32f) + (Vector2.UnitX * 256 * handSide) + (Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 30f * handSide)) * new Vector2(32, 96)); - - goalLocation += Main.player[brain.target].velocity * 24f; - float distToGoal = NPC.Center.Distance(goalLocation); - NPC.velocity = NPC.DirectionTo(goalLocation) * (2f + MathHelper.Clamp(distToGoal / 24f, 0f, 64f)); - } - else - { - if(Time == 0) - NPC.netUpdate = true; - - NPC.damage = NPC.defDamage; - NPC.knockBackResist = 0f; - - ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f); - - accel = 2f; - float speed = 12f; - - if (Time < brain.AIOverride().SwipeDelay) - { - if (!singleHand) - goalLocation = brain.Center + (Vector2.UnitY * -96f) + (Vector2.UnitX * (evenID ? -300 : 300)) + (Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 30f * (evenID ? -1 : 1))) * new Vector2(32, 96)); - else - goalLocation = brain.Center + (Vector2.UnitY * -96f) + (Vector2.UnitX * 300 * handSide) + (Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 30f * handSide)) * new Vector2(32, 96)); - - goalLocation += Main.player[brain.target].velocity * 24f; - NPC.velocity += NPC.DirectionTo(goalLocation) * accel; - NPC.velocity = NPC.velocity.ClampMagnitude(0f, speed); - } - else - { - if (!singleHand) - goalLocation = brain.Center + (Vector2.UnitY * -96f) + (Vector2.UnitX * (evenID ? -256 : 256)) + (Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 30f * (evenID ? -1 : 1))) * new Vector2(32, 96)); - else - goalLocation = brain.Center + (Vector2.UnitY * -96f) + (Vector2.UnitX * 256 * handSide) + (Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 30f * handSide)) * new Vector2(32, 96)); - - goalLocation.Y += MathHelper.Lerp(0, 420, CalamityUtils.SineInOutEasing(MathHelper.Clamp((Time - brain.AIOverride().SwipeDelay) / 20f, 0f, 1f), 1)); - - if (!singleHand) - goalLocation.X += MathHelper.Lerp(0f, 900f, CalamityUtils.SineInOutEasing(MathHelper.Clamp((Time - (brain.AIOverride().SwipeDelay + 5)) / 55f, 0f, 1f), 1)) * (evenID ? 1 : -1); - else - 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)); - } - - Time++; - } - - break; - case BrainAIState.CreeperCrush: - if(brain.AIOverride().AttackList.Contains(NPC.whoAmI)) - { - if (Time < 0) - Time = 0; - } - else - { - if (Time >= 0) - Time = -1; - } - - if (Time < 0) - { - baseRotation = (brain.Center - Main.player[brain.target].Center).ToRotation(); - evenID = CreeperID % 2 == 0; - goalLocation = brain.Center + Vector2.UnitX.RotatedBy(baseRotation + Math.Sin(bossCounter / 60f + CreeperID) * (evenID ? -1 : 1)) * (evenID ? 175 : 250); - if (NPC.DistanceSQ(goalLocation) > 9216) - { - NPC.velocity += NPC.DirectionTo(goalLocation); - NPC.velocity = NPC.velocity.ClampMagnitude(0f, 8f); - } - ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0f); - } - else - { - Player sharedTarget = Main.player[brain.target]; - Vector2 dashDir = AttackAngle.ToRotationVector2(); - if (!bocAI.OnSecondCreeperPhase) // Swipe Attack - { - float positioningTime = LightSwipeTravelTime + LightSwipeAttackDelay; - - 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; - } - else - { - AttackPosition = Vector2.Zero; - NPC.damage = NPC.defDamage; - NPC.knockBackResist = 0f; - int reelbackTime = 22; - - if (Time < (positioningTime + reelbackTime)) - { - float reelBackSpeedExponent = 2.6f; - float reelBackCompletion = Utils.GetLerpValue(0f, reelbackTime, Time - positioningTime, true); - float reelBackSpeed = MathHelper.Lerp(2.5f, 16f, MathF.Pow(reelBackCompletion, reelBackSpeedExponent)); - Vector2 reelBackVelocity = dashDir * -reelBackSpeed; - NPC.velocity = Vector2.Lerp(NPC.velocity, reelBackVelocity, 0.25f); - - if (Time == positioningTime + reelbackTime - 5) - SoundEngine.PlaySound(SoundID.DD2_MonkStaffSwing, NPC.Center); - } - else if (Time == (positioningTime + reelbackTime)) - NPC.velocity = dashDir * 32; - else - { - NPC.velocity *= 0.9f; - if (Time >= positioningTime + reelbackTime + 15) - { - NPC.damage = 0; - Time = -1; - brain.AIOverride().AttackList.Remove(NPC.whoAmI); - AttackPosition = Vector2.Zero; - ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0f); - break; - } - } - } - } - else //Crush Attack - { - float positioningTime = StrongSwipeTravelTime + StrongSwipeAttackDelay; - - if (Time <= positioningTime) - { - if (AttackPosition == Vector2.Zero) - AttackPosition = NPC.Center; - 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; - } - else - { - NPC.damage = NPC.defDamage; - NPC.knockBackResist = 0f; - int reelbackTime = 18; - float swingTime = 10f; - - if (Time <= (positioningTime + reelbackTime)) - { - float reelBackSpeedExponent = 2.6f; - float reelBackCompletion = Utils.GetLerpValue(0f, reelbackTime, Time - positioningTime, true); - float reelBackSpeed = MathHelper.Lerp(2.5f, 16f, MathF.Pow(reelBackCompletion, reelBackSpeedExponent)); - Vector2 reelBackVelocity = dashDir * -reelBackSpeed; - NPC.velocity = Vector2.Lerp(NPC.velocity, reelBackVelocity, 0.25f); - - if (Time == positioningTime + reelbackTime - 5) - SoundEngine.PlaySound(SoundID.DD2_MonkStaffSwing, NPC.Center); - - if (Time == (positioningTime + reelbackTime)) - AttackPosition = NPC.Center; - } - else if (Time <= (positioningTime + reelbackTime + swingTime)) - { - if (Main.npc[PartnerIndex].active) - { - float moveDist = 196; - NPC.Center = Vector2.Lerp(AttackPosition, AttackPosition + dashDir * moveDist, (Time - (positioningTime + reelbackTime)) / swingTime); - NPC.velocity = Vector2.Zero; - if (Time == (positioningTime + reelbackTime + swingTime)) - { - SoundEngine.PlaySound(SoundID.DD2_MonkStaffGroundImpact, NPC.Center); - SoundEngine.PlaySound(NPC.HitSound, NPC.Center); - NPC.velocity = dashDir * -8; - Vector2 attackCenter = AttackPosition + dashDir * 200; - if (dashDir.X <= 0) - { - //WaterFoam (0.25 -> 1), SoftRoundExplosion (0.025 -> 0.1), SmokeExplosion(0.05 -> 0.15) - CustomPulse splatter = new(attackCenter, Vector2.Zero, Color.Red, "CalamityMod/Particles/SmokeExplosion", Vector2.One, Main.rand.NextFloatDirection(), 0.05f, 0.15f, 24); - GeneralParticleHandler.SpawnParticle(splatter); - } - - if (Main.netMode != NetmodeID.MultiplayerClient) - for (int i = -1; i <= 1; i++) - Projectile.NewProjectile(NPC.GetSource_FromThis(), attackCenter, dashDir.RotatedBy(MathHelper.PiOver2 + (MathHelper.Pi / 6f * i)) * 8f, ProjectileID.BloodShot, BloodShotDamage, 0.5f); - } - } - else - NPC.velocity = dashDir * 19.6f; - } - else if (Time < (positioningTime + reelbackTime + swingTime + 30)) - { - NPC.velocity *= 0.96f; - } - else - { - NPC.damage = 0; - Time = -1; - brain.AIOverride().AttackList.Remove(NPC.whoAmI); - AttackPosition = Vector2.Zero; - ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0.5f); - break; - } - } - } - - ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f); - Time++; - } - break; - case BrainAIState.CreeperOrbit: - if (bossCounter == 0) - { - CachedValue1 = MathHelper.TwoPi / creeperCount * localCreeperID; - AttackAngle = 0; - } - float dist = OrbitStandardRadius + ((float)Math.Sin((CachedValue1 * 7) + bossCounter / 20f) * 24); - - if (brain.AIOverride().AttackList.Contains(NPC.whoAmI)) - { - if (Time < 0) - Time = 0; - } - else - { - if (Time >= 0) - Time = -1; - } - - if (Time >= 0) - { - float telegraphPeriod = OrbitAttackInterval * 0.25f; - float shiftPeriod = (OrbitAttackInterval - telegraphPeriod) / 2f; - if (Time < telegraphPeriod) - dist = MathHelper.Lerp(dist, OrbitTelegraphRadius, CalamityUtils.SineOutEasing(Time / telegraphPeriod, 1)); - else if (Time < shiftPeriod + telegraphPeriod) - dist = MathHelper.Lerp(OrbitTelegraphRadius, 16, CalamityUtils.SineInOutEasing((Time - telegraphPeriod) / shiftPeriod, 1)); - else - { - dist = MathHelper.Lerp(16, dist, CalamityUtils.SineInOutEasing((Time - telegraphPeriod - shiftPeriod) / shiftPeriod, 1)); - if (Time > OrbitAttackInterval) - { - Time = -2; - brain.AIOverride().AttackList.Remove(NPC.whoAmI); - } - } - ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f, 0.1f); - Time++; - } - else - ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0f, 0.05f); - - 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; - goalLocation = target.Center + rotation; - if (bossCounter < OrbitSetupDuration) - NPC.Center = Vector2.Lerp(AttackPosition, goalLocation, CalamityUtils.SineOutEasing(bossCounter / OrbitSetupDuration, 1)); - else - NPC.Center = goalLocation; - } - 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); - } - - goalLocation = AttackPosition + rotation; - NPC.Center = goalLocation; - } - break; - case BrainAIState.CreeperSpiral: - int tendrilID = (CreeperID % TendrilCount) + 1; - - if (bossCounter == 0) - { - AttackPosition = Vector2.Zero; - 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; - } - - int index = (int)CachedValue1; - int groupCount = CachedValue2; - float placementRatio = (index + 1) / (float)(groupCount + 1); - - float spiralAngle = bocAI.AttackRotation; - float goalAngle = spiralAngle + ((MathHelper.TwoPi / TendrilCount) * tendrilID); - - float angularVelocity = (goalAngle - AttackAngle) / (16f + (placementRatio * 16f)); - - AttackAngle += angularVelocity; - - float goalRadius = TendrilStartDistance + (TendrilLength * placementRatio); - goalRadius += (float)Math.Sin(bossCounter / 20f) * MathHelper.Lerp(MaxCreeperSway, 0, groupCount / (float)(GetBrainOfCthuluCreepersCountRevDeath() / 3)) * (index % 2 == 0 ? -1 : 1); - - Vector2 position = brain.Center + (AttackAngle.ToRotationVector2() * goalRadius); - if (bossCounter >= SpiralSetupTime) - { - NPC.Center = position; - - NPC.damage = NPC.defDamage; - NPC.knockBackResist = 0f; - - ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f); - } - else if (bossCounter < SpiralSetupTime / 10f) - 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)); - } - break; - } - - else - switch (AIState) - { - case CreeperAIState.Idle: - if (Time == 0) - { - AIState = CreeperAIState.Charge; - break; - } - - NPC.knockBackResist = 0.72f; - NPC.damage = 0; - - float baseRotation = MathHelper.TwoPi / (GetBrainOfCthuluCreepersCountRevDeath() / 2f) * (CreeperID / 2f); - Vector2 goalLocation = brain.Center + (Vector2.UnitX * (evenID ? -256 : 256)) + Vector2.UnitX.RotatedBy(baseRotation + (bossCounter / 60f * (evenID ? -1 : 1))) * 64; - if (NPC.DistanceSQ(goalLocation) > 9216) - { - NPC.velocity += NPC.DirectionTo(goalLocation); - NPC.velocity = NPC.velocity.ClampMagnitude(0f, 8f); - } - ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0f); - Time = -1; - AttackPosition = Vector2.Zero; - break; - case CreeperAIState.Charge: - Player target = Main.player[NPC.target]; - - if (Time < CreeperChargePositioningTime) - { - goalLocation = target.Center + ((NPC.Center - target.Center).SafeNormalize(-Vector2.UnitY).RotatedBy((evenID ? -MathHelper.PiOver4 : MathHelper.PiOver4)) * 96); - if (NPC.DistanceSQ(goalLocation) > 4096) - { - NPC.velocity += NPC.DirectionTo(goalLocation); - NPC.velocity = NPC.velocity.ClampMagnitude(0f, 12f); - } - ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f); - } - else - { - NPC.damage = NPC.defDamage; - NPC.knockBackResist = 0f; - - if (Time < (CreeperChargePositioningTime + CreeperChargeWindUpTime)) - { - float reelBackSpeedExponent = 2.6f; - float reelBackCompletion = Utils.GetLerpValue(0f, CreeperChargeWindUpTime, Time - CreeperChargePositioningTime, true); - float reelBackSpeed = MathHelper.Lerp(2.5f, 16f, MathF.Pow(reelBackCompletion, reelBackSpeedExponent)); - Vector2 reelBackVelocity = NPC.DirectionTo(Main.player[brain.target].Center) * -reelBackSpeed; - NPC.velocity = Vector2.Lerp(NPC.velocity, reelBackVelocity, 0.25f); - - if (Time == CreeperChargePositioningTime + CreeperChargeWindUpTime - 5) - SoundEngine.PlaySound(SoundID.DD2_MonkStaffSwing, NPC.Center); - } - else if (Time == CreeperChargePositioningTime + CreeperChargeWindUpTime) - NPC.velocity = NPC.DirectionTo(Main.player[brain.target].Center) * 24; - else - { - NPC.velocity *= 0.975f; - if (Time >= CreeperChargePositioningTime + CreeperChargeWindUpTime + 30) - { - NPC.damage = 0; - Time = -10; - AIState = CreeperAIState.Idle; - break; - } - } - } - Time++; - break; - } - - FlowTime += 0.01f * (2 * (1 + ConnectionOpacity)); - - return false; - } - - public override void SendExtraAI(BitWriter bitWriter, BinaryWriter binaryWriter) - { - binaryWriter.Write(Time); - binaryWriter.Write(CachedValue2); - binaryWriter.Write(PartnerIndex); - - binaryWriter.WritePackedVector2(AttackPosition); - - } - - public override void ReceiveExtraAI(BitReader bitReader, BinaryReader binaryReader) - { - Time = binaryReader.ReadInt32(); - CachedValue2 = binaryReader.ReadInt32(); - PartnerIndex = binaryReader.ReadInt32(); - - AttackPosition = binaryReader.ReadPackedVector2(); - } - - public override void HitEffect(Mod mod, NPC.HitInfo hit) - { - if(NPC.life <= 0) - { - List verletTendril = RevBoCSystem.VerletTendrils[NPC.AIOverride().CreeperID]; - if (verletTendril is null) - return; - - for (int i = 0; i < verletTendril.Count; i++) - { - Vector2 start = verletTendril[i].position; - Vector2 end = i == verletTendril.Count - 1 ? NPC.Center : verletTendril[i + 1].position; - - float rotation = (end - start).ToRotation(); - - float dist = Vector2.Distance(start, end); - Vector2 scale = new(1f, dist / RevBoCSystem.tendril.Height()); - - BrokenTendril gore = new(start, Vector2.UnitY.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver4, MathHelper.PiOver4)) * -Main.rand.NextFloat(2f, 4f), rotation, scale, 60); - GeneralParticleHandler.SpawnParticle(gore); - - } - - RevBoCSystem.VerletTendrils[NPC.AIOverride().CreeperID] = []; - } - } - - public override bool PreDraw(Mod mod, SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) => false; - } - } - - public class RevBoCSystem : ModSystem - { - internal static Asset tendril; - private static Texture2D tendrilGlow = null; - private static Texture2D brainGlow = null; - private static Texture2D creeperGlow = null; - - internal static float ScreenBlurStrength = 0f; - - internal static List[] VerletTendrils = new List[BrainOfCthulhuAI.GetBrainOfCthuluCreepersCountRevDeath()]; - - private static int previousMusic = -1; - public static int PreviousMusic => previousMusic; - - public override void OnModLoad() - { - if (!Main.dedServ) - { - tendril = ModContent.Request("Terraria/Images/Chain12"); - } - - On_NPC.SpawnBoss += SpawnBrainNoMessage; - On_Player.ItemCheck_UseBossSpawners += BlockRoar; - On_Main.UpdateAudio_DecideOnNewMusic += StopBoss3FromStarting; - On_Main.UpdateAudio_DecideOnTOWMusic += StopOWBoss1FromStarting; - } - - private void StopBoss3FromStarting(On_Main.orig_UpdateAudio_DecideOnNewMusic orig, Main self) - { - orig(self); - - if (NPC.crimsonBoss == -1 || !CalamityWorld.revenge) - 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)) - { - if (Main.newMusic == MusicID.Boss3) - Main.newMusic = previousMusic; - - if (Main.curMusic == MusicID.Boss3) - Main.curMusic = previousMusic; - } - } - - private void StopOWBoss1FromStarting(On_Main.orig_UpdateAudio_DecideOnTOWMusic orig, Main self) - { - orig(self); - - if (NPC.crimsonBoss == -1 || !CalamityWorld.revenge) - 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)) - { - if (Main.newMusic == MusicID.OtherworldlyBoss1) - Main.newMusic = previousMusic; - - if (Main.curMusic == MusicID.OtherworldlyBoss1) - Main.curMusic = previousMusic; - } - } - - private void BlockRoar(On_Player.orig_ItemCheck_UseBossSpawners orig, Player self, int onWhichPlayer, Item sItem) - { - if (sItem.type != ItemID.BloodySpine || !CalamityWorld.revenge || !self.ItemTimeIsZero || self.itemAnimation <= 0) - { - orig(self, onWhichPlayer, sItem); - return; - } - - SoundEngine.PlaySound(SoundID.NPCDeath1, Main.LocalPlayer.Center); - - if (self.ZoneCrimson) - { - self.ApplyItemTime(sItem); - CalamityUtils.SpawnBossUsingItem(self, NPCID.BrainofCthulhu); - } - } - - private void SpawnBrainNoMessage(On_NPC.orig_SpawnBoss orig, int spawnPositionX, int spawnPositionY, int Type, int targetPlayerIndex) - { - if (Type != NPCID.BrainofCthulhu || !CalamityWorld.revenge) - { - orig(spawnPositionX, spawnPositionY, Type, targetPlayerIndex); - return; - } - - int num = NPC.NewNPC(NPC.GetBossSpawnSource(targetPlayerIndex), spawnPositionX, spawnPositionY, Type, 1); - - if (num == 200 || num == -1) - return; - - if (Main.player[targetPlayerIndex].HeldItem.type == ItemID.BloodySpine) - BrainOfCthulhuAI.SummonedViaItem = true; - - NPC.crimsonBoss = num; - Main.npc[num].target = targetPlayerIndex; - Main.npc[num].timeLeft *= 20; - - previousMusic = Main.curMusic; - - if (Main.netMode == NetmodeID.Server && num < 200) - NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, num); - } - - internal static Texture2D GetTendrilGlow() - { - if(tendrilGlow == null) - { - var tex = new Texture2D(Main.graphics.GraphicsDevice, tendril.Value.Width, tendril.Value.Height); - - var BaseArray = new Color[tex.Width * tex.Height]; - var ColorArray = new Color[tex.Width * tex.Height]; - tendril.Value.GetData(BaseArray); - for (var i = 0; i < BaseArray.Length; i++) - { - ColorArray[i] = new Color(255, 255, 255) * (((float)BaseArray[i].A) / 255f); - } - tex.SetData(ColorArray); - tendrilGlow = tex; - } - return tendrilGlow; - } - - internal static Texture2D GetBrainGlow() - { - if (brainGlow == null) - { - var tex = new Texture2D(Main.graphics.GraphicsDevice, TextureAssets.Npc[NPCID.BrainofCthulhu].Value.Width, TextureAssets.Npc[NPCID.BrainofCthulhu].Value.Height); - - var BaseArray = new Color[tex.Width * tex.Height]; - var ColorArray = new Color[tex.Width * tex.Height]; - TextureAssets.Npc[NPCID.BrainofCthulhu].Value.GetData(BaseArray); - for (var i = 0; i < BaseArray.Length; i++) - { - ColorArray[i] = new Color(255, 255, 255) * (((float)BaseArray[i].A) / 255f); - } - tex.SetData(ColorArray); - brainGlow = tex; - } - return brainGlow; - } - - internal static Texture2D GetCreeperGlow() - { - if (creeperGlow == null) - { - var tex = new Texture2D(Main.graphics.GraphicsDevice, TextureAssets.Npc[NPCID.Creeper].Value.Width, TextureAssets.Npc[NPCID.Creeper].Value.Height); - - var BaseArray = new Color[tex.Width * tex.Height]; - var ColorArray = new Color[tex.Width * tex.Height]; - TextureAssets.Npc[NPCID.Creeper].Value.GetData(BaseArray); - for (var i = 0; i < BaseArray.Length; i++) - { - ColorArray[i] = new Color(255, 255, 255) * (((float)BaseArray[i].A) / 255f); - } - tex.SetData(ColorArray); - creeperGlow = tex; - } - return creeperGlow; - } - - public override void PostUpdateNPCs() - { - if (!NPC.AnyNPCs(NPCID.BrainofCthulhu)) - BrainOfCthulhuAI.SummonedViaItem = false; - - if (Main.netMode != NetmodeID.Server) - { - if (NPC.crimsonBoss != -1 && CalamityWorld.revenge && Main.npc[NPC.crimsonBoss].ai[0] < (float)BrainOfCthulhuAI.BrainAIState.Phase2TransitionClosed) - { - List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper).ToList(); - - foreach (NPC creeper in creepers) - { - int creeperID = (int)creeper.ai[0]; - - Vector2 startPoint = Main.npc[NPC.crimsonBoss].Center + Vector2.UnitY * 32; - - float creeperRatio = creeperID / (float)BrainOfCthulhuAI.GetBrainOfCthuluCreepersCountRevDeath(); - if (creeperID % 2 == 0) - startPoint += new Vector2(MathHelper.Lerp(-24, 0, creeperRatio), 0); - else - startPoint += new Vector2(MathHelper.Lerp(24, 0, creeperRatio), 0); - - Vector2 endPoint = creeper.Center; - - List tendril = VerletTendrils[creeperID]; - if (tendril is null || tendril.Count == 0) - continue; - - tendril[0].position = startPoint; - tendril[0].locked = true; - tendril[^1].position = endPoint; - tendril[^1].locked = true; - - VerletSimulatedSegment.SimpleSimulation(tendril, 16, 10, 3); - } - } - } - } - - public override void PostDrawTiles() - { - if (Main.netMode != NetmodeID.Server) - { - if (NPC.crimsonBoss == -1 || !CalamityWorld.revenge || Main.npc[NPC.crimsonBoss].ai[0] >= (float)BrainOfCthulhuAI.BrainAIState.Phase2TransitionClosed) - { - Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().UseOpacity(0); - if (Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].IsActive()) - Filters.Scene.Deactivate("CalamityMod:BrainOfCthulhuForcefield"); - } - else - { - if (!Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].IsActive()) - Filters.Scene.Activate("CalamityMod:BrainOfCthulhuForcefield"); - - NPC target = Main.npc[NPC.crimsonBoss]; - Vector2 targetPos = target.Center; - float shieldOpacity = target.AIOverride().ShieldOpacity; - float shieldScale = target.AIOverride().ShieldScale; - targetPos = Vector2.Transform(targetPos - Main.screenPosition, Main.GameViewMatrix.ZoomMatrix) / Main.ScreenSize.ToVector2(); - - Texture2D voronoi = ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/VoronoiShapes3").Value; - Texture2D depthNoise = ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Veins").Value; - - Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().Shader.Parameters["voronoi"].SetValue(voronoi); - Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().Shader.Parameters["depthNoise"].SetValue(depthNoise); - Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().Shader.Parameters["uScreenResolution"].SetValue(new Vector2(Main.graphics.GraphicsDevice.Viewport.Width, Main.graphics.GraphicsDevice.Viewport.Height)); - Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().UseProgress(0.15f * shieldScale); - Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().UseOpacity(shieldOpacity); - Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().UseColor(Color.Red); - Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().UseSecondaryColor(new Color(255, 0, 90)); //Crimson color (R:220,G:20,B:60,A:255). // Magenta color (R:255,G:0,B:255,A:255). - Filters.Scene["CalamityMod:BrainOfCthulhuForcefield"].GetShader().UseDirection(targetPos); - } - - if (ScreenBlurStrength == 0f) - { - Filters.Scene["CalamityMod:RadialBlurShader"].GetShader().UseIntensity(0); - if (Filters.Scene["CalamityMod:RadialBlurShader"].IsActive()) - Filters.Scene.Deactivate("CalamityMod:RadialBlurShader"); - return; - } - - if (NPC.crimsonBoss == -1) - { - ScreenBlurStrength = Filters.Scene["CalamityMod:RadialBlurShader"].GetShader().Intensity * 0.9f; - Filters.Scene["CalamityMod:RadialBlurShader"].GetShader().UseIntensity(ScreenBlurStrength); - if (ScreenBlurStrength < 0.01f) - ScreenBlurStrength = 0f; - return; - } - - if (Filters.Scene["CalamityMod:RadialBlurShader"].IsLoaded) - { - if (!Filters.Scene["CalamityMod:RadialBlurShader"].IsActive()) - Filters.Scene.Activate("CalamityMod:RadialBlurShader"); - NPC boss = Main.npc[NPC.crimsonBoss]; - float counter = boss.ai[1] - boss.ai[2] - 240; - float distSQ = Main.LocalPlayer.DistanceSQ(boss.Center); - float distanceScaleFactor = 1; - if (distSQ > 592900) //770^2 - distanceScaleFactor = 1 / (1 + (((float)Math.Sqrt(distSQ) - 770) / 32f)); - - Filters.Scene["CalamityMod:RadialBlurShader"].GetShader().UseIntensity((ScreenBlurStrength + (((float)Math.Cos(counter * MathHelper.TwoPi / 15f) / 2f + 0.5f) * (0.4f * ScreenBlurStrength))) * distanceScaleFactor); - Filters.Scene["CalamityMod:RadialBlurShader"].GetShader().Shader.Parameters["uSaturation"].SetValue(20); - - Vector2 targetPos = Vector2.Transform(boss.Center - Main.screenPosition, Main.GameViewMatrix.ZoomMatrix) / Main.ScreenSize.ToVector2(); - - Filters.Scene["CalamityMod:RadialBlurShader"].GetShader().UseDirection(targetPos); - - } - } - } - - public override void PostUpdateEverything() - { - if (Main.curMusic != MusicID.Boss3 && Main.curMusic != MusicID.OtherworldlyBoss1) - previousMusic = Main.curMusic; - - if (previousMusic == -1) - previousMusic = MusicID.Crimson; - - } - } - - public class BrokenTendril : Particle - { - public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; - - public override bool UseCustomDraw => true; - - private int TimeLeft; - private float Opacity = 1f; - private Vector2 InitalScale = Vector2.One; - - public BrokenTendril(Vector2 position, Vector2 velocity, float rotation, Vector2 scale, int lifeTime) - { - Position = position; - Velocity = velocity; - Scale = 1f; - Rotation = rotation; - TimeLeft = lifeTime; - InitalScale = scale - Vector2.One; - } - - public override void Update() - { - if (InitalScale != Vector2.Zero) - { - InitalScale *= 0.98f; - if (InitalScale.X < 0.05f) - InitalScale.X = 0; - if (InitalScale.Y < 0.05f) - InitalScale.Y = 0; - } - - Point tilePos = Position.ToTileCoordinates(); - if(!WorldGen.InWorld(tilePos.X, tilePos.Y)) - { - Kill(); - return; - } - - if (Main.tile[tilePos].IsTileSolid() || TileID.Sets.Platforms[Main.tile[tilePos].TileType]) - { - Velocity.Y = 0; - if (Velocity.X > 0.05f) - Velocity.X *= 0.9f; - else - Velocity.X = 0; - } - else - { - Velocity.Y += 0.25f; - Velocity.X *= 0.975f; - } - - Rotation += Velocity.X * 0.025f; - - if (Velocity == Vector2.Zero) - { - if (TimeLeft < 30) - { - Opacity = TimeLeft / 30f; - if (TimeLeft <= 0) - Kill(); - } - TimeLeft--; - } - } - - public override void CustomDraw(SpriteBatch spriteBatch) - { - Texture2D tex = RevBoCSystem.tendril.Value; - float rot = Rotation - MathHelper.PiOver2; - Vector2 center = Position + rot.ToRotationVector2() * tex.Size().Y * InitalScale.Y * 0.5f; - spriteBatch.Draw(tex, Position - Main.screenPosition, null, Lighting.GetColor(center.ToTileCoordinates()) * Opacity, rot, tex.Size() * Vector2.UnitX * 0.5f, Vector2.One + InitalScale, SpriteEffects.None, 0f); - } - } - - public class BrainofCthulhuAfterImage : Particle - { - public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; - - public override bool UseCustomDraw => false; - - public override bool SetLifetime => true; - - private float StartFade; - private float Opacity = 1f; - List Path; - private Vector2 MyScale = Vector2.One; - private Rectangle Frame; - - public BrainofCthulhuAfterImage(BezierCurve path, float rotation, Vector2 scale, int lifeTime, Rectangle frame, float startFadeRatio = 0f) - { - Path = path.GetPoints(lifeTime); - Position = Path[0]; - Rotation = rotation; - StartFade = startFadeRatio; - MyScale = scale; - Frame = frame; - Lifetime = lifeTime + 1; - } - - public override void Update() - { - float timeRatio = Time / (float)Lifetime; - Opacity = timeRatio; - if (StartFade != 0f) - Opacity = Utils.GetLerpValue(StartFade, 1f, timeRatio, true); - - Opacity = 1 - CalamityUtils.SineInEasing(Opacity, 1); - - List pathPosition = Path; - - if(Time >= pathPosition.Count) - { - Kill(); - return; - } - - Position = pathPosition[Time]; - } - - public override void CustomDraw(SpriteBatch spriteBatch) - { - float timeRatio = Time / (float)Lifetime; - spriteBatch.Draw(TextureAssets.Npc[NPCID.BrainofCthulhu].Value, Position - Main.screenPosition, Frame, Lighting.GetColor(Position.ToTileCoordinates()) * Opacity * 0.5f, Rotation, Frame.Size() * 0.5f, MyScale, 0, 0); - } - } - - public class BossRoar : Particle - { - public override string Texture => "CalamityMod/Particles/RoarPulse"; - public override bool SetLifetime => true; - public override bool UseCustomDraw => true; - - private float OriginalScale; - private float FinalScale; - private float BaseOpacity; - private float opacity; - private Color BaseColor; - - public BossRoar(Vector2 position, Color color, float rotation, float originalScale, float finalScale, int lifeTime, float baseOpacity = 1f) - { - Position = position; - BaseColor = color; - OriginalScale = originalScale; - FinalScale = finalScale; - Scale = originalScale; - Lifetime = lifeTime; - BaseOpacity = baseOpacity; - Rotation = rotation; - } - - public override void Update() - { - Scale = MathHelper.Lerp(OriginalScale, FinalScale, LifetimeCompletion); - - opacity = 1f; - if (LifetimeCompletion < 0.1f) - opacity = MathHelper.Lerp(0f, 1f, LifetimeCompletion * 10); - - Color = BaseColor * opacity; - } - - public override void CustomDraw(SpriteBatch spriteBatch) - { - Texture2D tex = ModContent.Request(Texture).Value; - spriteBatch.Draw(tex, Position - Main.screenPosition, null, Color * BaseOpacity, Rotation, tex.Size() / 2f, Scale, SpriteEffects.None, 0); - } - } - - [AutoloadBossHead] - public class BrainIllusion : ModNPC, ILocalizedModType - { - public new string LocalizationCategory => "NPCs"; - public override string Texture => "Terraria/Images/NPC_266"; - public override string BossHeadTexture => "Terraria/Images/NPC_Head_Boss_23"; - - ref float Time => ref NPC.ai[0]; - - ref float AttackValue => ref NPC.ai[1]; - - ref float Angle => ref NPC.ai[2]; - - ref float TeleportDuration => ref NPC.localAI[0]; - - ref float TeleportTime => ref NPC.ai[3]; - - public override void SetStaticDefaults() - { - this.HideFromBestiary(); - Main.npcFrameCount[Type] = 8; - } - - public override void SetDefaults() - { - NPC.width = 160; - NPC.height = 110; - NPC.damage = 20; - NPC.lifeMax = 1; - NPC.knockBackResist = 0f; - NPC.noGravity = true; - NPC.noTileCollide = true; - NPC.boss = true; - NPC.dontTakeDamage = true; - NPC.chaseable = false; - NPC.npcSlots = 0f; - NPC.netAlways = true; - Music = MusicID.Boss3; - } - - public override void OnSpawn(IEntitySource source) - { - TeleportDuration = AttackValue; - AttackValue = 0; - TeleportTime = Time; - } - - public override void AI() - { - if(NPC.crimsonBoss == -1) - { - NPC.active = false; - return; - } - NPC brain = Main.npc[NPC.crimsonBoss]; - Player target = Main.player[brain.target]; - NPC.GivenName = brain.GivenOrTypeName + $": {brain.life}/{brain.lifeMax}"; - - #region Attack Start - if (Time < 30) - { - TeleportDuration = 30; - - if (Time == (TeleportDuration / 2f) && AttackValue == 0) - { - AttackValue = 1; - } - else - { - TeleportTime--; - } - - NPC.Opacity = 1 - (TeleportTime / (TeleportDuration / 2f)); - } - #endregion - else - { - if (Time == 30) - { - NPC.oldPos[0] = NPC.Center; - TeleportTime = 0; - AttackValue = 0; - NPC.Opacity = 1f; - } - 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); - Angle += MathHelper.Lerp(0f, BrainOfCthulhuAI.IllusionDashStartingSpinSpeed, CalamityUtils.SineInEasing(lerp, 1)); - } - else if (Time <= 60f + BrainOfCthulhuAI.IllusionDashSpinDuration) - { - NPC.Center = target.Center + Angle.ToRotationVector2() * BrainOfCthulhuAI.IllusionDashCloseInDistance; - - Angle += MathHelper.Lerp(BrainOfCthulhuAI.IllusionDashStartingSpinSpeed, 0f, CalamityUtils.SineOutEasing((Time - 60) / (float)BrainOfCthulhuAI.IllusionDashSpinDuration, 1)); - } - else if (Time <= 90 + BrainOfCthulhuAI.IllusionDashSpinDuration) - { - float reelBackSpeedExponent = 2.6f; - float reelBackCompletion = Utils.GetLerpValue(0f, 30, Time - (60 + BrainOfCthulhuAI.IllusionDashSpinDuration), true); - float reelBackSpeed = MathHelper.Lerp(4f, 20f, MathF.Pow(reelBackCompletion, reelBackSpeedExponent)); - Vector2 reelBackVelocity = (Angle + MathHelper.Pi).ToRotationVector2() * -reelBackSpeed; - NPC.velocity = Vector2.Lerp(NPC.velocity, reelBackVelocity, 0.25f); - } - else if (Time == 91 + BrainOfCthulhuAI.IllusionDashSpinDuration) - NPC.velocity = (Angle + MathHelper.Pi).ToRotationVector2() * BrainOfCthulhuAI.IllusionDashVelocity; - else if (Time <= 91 + BrainOfCthulhuAI.IllusionDashSpinDuration + BrainOfCthulhuAI.IllusionDashTeleportDuration) - { - NPC.Opacity = MathHelper.Lerp(1f, 0.25f, CalamityUtils.SineInEasing((Time - (91 + BrainOfCthulhuAI.IllusionDashSpinDuration)) / (float)BrainOfCthulhuAI.IllusionDashTeleportDuration, 1)); - if (NPC.Opacity < 0.666f) - NPC.damage = 0; - } - else - NPC.active = false; - } - - Time++; - } - - public override void FindFrame(int frameHeight) - { - NPC.frameCounter += 1.0; - if (NPC.frameCounter > 6.0) - { - NPC.frameCounter = 0.0; - NPC.frame.Y += frameHeight; - } - - if (NPC.frame.Y < frameHeight * 4) - { - NPC.frame.Y = frameHeight * 4; - } - if (NPC.frame.Y > frameHeight * 7) - { - NPC.frame.Y = frameHeight * 4; - } - } - - public override bool? CanBeHitByItem(Player player, Item item) => false; - public override bool? CanBeHitByProjectile(Projectile projectile) => false; - - public override bool PreDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) - { - Vector2 drawPos = NPC.Center + (Vector2.UnitY * 16) - Main.screenPosition; - Vector2 scale = Vector2.One; - - if (TeleportTime != 0) - { - //Color glowColor = Color.White * (teleportCounter / 30f); - scale = Vector2.Lerp(Vector2.One, new Vector2(0.5f + ((float)Math.Cos(Time / (TeleportDuration / 2f) * MathHelper.TwoPi) / 2f + 0.5f), 0.5f + ((float)Math.Sin(Time / (TeleportDuration / 2f) * MathHelper.TwoPi) / 2f + 0.5f)), CalamityUtils.SineInOutEasing(TeleportTime / (TeleportDuration / 2f), 1)); - - spriteBatch.Draw(TextureAssets.Npc[NPCID.BrainofCthulhu].Value, drawPos, NPC.frame, Lighting.GetColor(NPC.Center.ToTileCoordinates()) * NPC.Opacity, NPC.rotation, NPC.frame.Size() * 0.5f, scale * NPC.scale, 0, 0); - //spriteBatch.Draw(GetBrainGlow(), drawPos, npc.frame, glowColor, npc.rotation, npc.frame.Size() * 0.5f, scale, 0, 0); - } - else - spriteBatch.Draw(TextureAssets.Npc[NPCID.BrainofCthulhu].Value, drawPos, NPC.frame, Lighting.GetColor(NPC.Center.ToTileCoordinates()) * NPC.Opacity, NPC.rotation, NPC.frame.Size() * 0.5f, scale * NPC.scale, 0, 0); - return false; - } - } - - [AutoloadBossHead] - public class FalseBrain : ModNPC, ILocalizedModType - { - public new string LocalizationCategory => "NPCs"; - public override string Texture => "CalamityMod/NPCs/VanillaNPCAIOverrides/Bosses/FalseBrain"; - public override string BossHeadTexture => "Terraria/Images/NPC_Head_Boss_23"; - - public override void SetStaticDefaults() - { - this.HideFromBestiary(); - Main.npcFrameCount[Type] = 4; - } - - public override void SetDefaults() - { - NPC.width = 160; - NPC.height = 110; - NPC.damage = 0; - NPC.lifeMax = 1; - NPC.knockBackResist = 0f; - NPC.noGravity = true; - NPC.noTileCollide = true; - NPC.boss = true; - NPC.immortal = true; - NPC.dontTakeDamage = true; - NPC.chaseable = false; - NPC.npcSlots = 0f; - NPC.netAlways = true; - NPC.ShowNameOnHover = false; - Music = MusicID.Boss3; - - NPC.localAI[0] = Main.rand.Next(5); - NPC.localAI[1] = 1 + Main.rand.NextFloat(-0.5f, 0.5f); - } - private int Variant => (int)NPC.localAI[0]; - private float Angle => NPC.ai[0]; - private ref float Time => ref NPC.ai[1]; - internal bool BeenHit = false; - int AttackTime = 0; - int SpawnTime = 60; - - internal static float TimeDivisor => 360f; - internal float DrawPriority => (float)Math.Cos(-Time * MathHelper.TwoPi / TimeDivisor); - internal static List blackListedProjectiles = []; - - public override void AI() - { - if(NPC.crimsonBoss == -1) - { - NPC.active = false; - return; - } - - NPC brain = Main.npc[NPC.crimsonBoss]; - NPC.GivenName = brain.GivenOrTypeName + $": {brain.life}/{brain.lifeMax}"; - - if (BeenHit) - { - NPC.dontTakeDamage = true; - - if(AttackTime == 60) - NPC.active = false; - - AttackTime++; - } - else - { - float lerp = CalamityUtils.SineInOutEasing(MathHelper.Clamp(SpawnTime / -30f, 0f, 1f), 1); - float baseDist = 240; - float circleDist = 480; - if (SpawnTime != -30) - { - baseDist = MathHelper.Lerp(480, 240, lerp); - circleDist = MathHelper.Lerp(240, 480, lerp); - } - NPC.Center = brain.AIOverride().AttackPosition + Vector2.UnitX.RotatedBy(Angle) * (baseDist + (circleDist * ((float)Math.Sin(-Time * MathHelper.TwoPi / TimeDivisor) / 2f + 0.5f))); - NPC.Center += Vector2.UnitX.RotatedBy(Angle + MathHelper.PiOver2) * (90 * (float)Math.Cos(Time * MathHelper.TwoPi / TimeDivisor)); - } - - if (SpawnTime > 0) - { - if (--SpawnTime == 0) - NPC.dontTakeDamage = false; - } - else if (SpawnTime > -30) - Time += --SpawnTime / -30f; - else - Time++; - } - - public override void OnHitByItem(Player player, Item item, NPC.HitInfo hit, int damageDone) - { - SmiteFool(player); - } - - public override void OnHitByProjectile(Projectile projectile, NPC.HitInfo hit, int damageDone) - { - if (!projectile.Calamity().IgnoreBoCIllusions && projectile.owner != -1) - SmiteFool(Main.player[projectile.owner]); - } - - private void SmiteFool(Player fool) - { - if (!BeenHit) - { - for(int i = 0; i < 6; i++) - { - Vector2 dir = fool.Center - NPC.Center; - int lifeTime = 24; - dir /= lifeTime / 2f * 5f; - dir *= i; - DirectionalPulseRing pulse = new(NPC.Center, dir, i % 2 == 0 ? Color.Red : Color.Orange, new Vector2(0.5f, 1), dir.ToRotation(), 0f, i / 5f, lifeTime + 8); - GeneralParticleHandler.SpawnParticle(pulse); - } - - BeenHit = true; - SoundEngine.PlaySound(SoundID.Zombie105, NPC.Center); //LC Laugh - fool.AddBuff(BuffID.Darkness, 900); - fool.AddBuff(BuffID.Bleeding, 900); - fool.AddBuff(BuffID.Confused, 60); - int timeToAdd = 600; - int bbIndex = fool.buffType.ToList().IndexOf(ModContent.BuffType()); - if (bbIndex != -1) - { - timeToAdd /= 2; - timeToAdd += fool.buffTime[bbIndex]; - } - fool.AddBuff(ModContent.BuffType(), timeToAdd); - - fool.Calamity().adrenaline = 0; - - NPC.dontTakeDamage = true; - } - } - - public override void FindFrame(int frameHeight) - { - NPC.frameCounter += 0.2f * NPC.localAI[1]; - if ((int)NPC.frameCounter > 3) - NPC.frameCounter = 0; - } - - internal void DrawSelf(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) - { - Texture2D tex = TextureAssets.Npc[Type].Value; - - Rectangle frame = tex.Frame(5, 4, Variant, (int)NPC.frameCounter); - - Vector2 scaleDistort = new Vector2((float)Math.Cos(Main.GlobalTimeWrappedHourly * MathHelper.TwoPi * 2) / 2f, (float)Math.Sin(Main.GlobalTimeWrappedHourly * MathHelper.TwoPi * 2) / 2f); - - float endLerp = AttackTime / 60f; - float startLerp = SpawnTime / 60f; - - if (SpawnTime > 0) - { - drawColor *= (1 - startLerp); - scaleDistort *= startLerp; - } - else - { - drawColor = Color.Lerp(drawColor, Color.Red, endLerp) * (1 - endLerp); - scaleDistort *= endLerp; - } - - spriteBatch.Draw(tex, NPC.Center + (Vector2.UnitY * 16) - screenPos, frame, drawColor, NPC.rotation, frame.Size() * 0.5f, (Vector2.One + scaleDistort) * NPC.scale, 0, 0); - } - - public override bool PreDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) => false; - } - - public class BloodScythe : ModProjectile, ILocalizedModType - { - public new string LocalizationCategory => "Projectiles.Boss"; - public override string Texture => "CalamityMod/Particles/VerticalSmearRagged"; - - private Vector2 InitialVelocity = Vector2.Zero; - private Vector2 AcceleratingVelocity = Vector2.Zero; - private static float RotationSpeed => MathHelper.Pi / 8f; - private static float Acceleration => 0.175f; - private static int Lifetime => 240; - - public override void SetStaticDefaults() - { - ProjectileID.Sets.TrailCacheLength[Type] = 16; - ProjectileID.Sets.TrailingMode[Type] = 2; - } - - public override void SetDefaults() - { - Projectile.width = 300; - Projectile.height = 300; - Projectile.penetrate = -1; - Projectile.Opacity = 1f; - Projectile.tileCollide = false; - Projectile.timeLeft = Lifetime; - Projectile.damage = 10; - Projectile.scale = 0.1f; - Projectile.hostile = true; - } - - public override void OnSpawn(IEntitySource source) - { - InitialVelocity = Projectile.velocity; - Projectile.rotation = Projectile.velocity.ToRotation(); - for (int i = 0; i < 3; i++) - { - BloodParticle p = new(Projectile.Center, Projectile.velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 6f, MathHelper.Pi / 6f)) * Main.rand.NextFloat(0.5f, 1f), 32, 1f, Color.Red); - GeneralParticleHandler.SpawnParticle(p); - } - BloodParticle2 p2 = new(Projectile.Center, Projectile.velocity * 0.75f, 16, 0.5f, Color.Red); - GeneralParticleHandler.SpawnParticle(p2); - } - - public override void AI() - { - int UpTime = Lifetime - Projectile.timeLeft; - InitialVelocity *= 0.925f; - if (UpTime > 15) - { - AcceleratingVelocity += Projectile.velocity.SafeNormalize(InitialVelocity.SafeNormalize(Vector2.UnitX)) * Acceleration; - if (Main.rand.NextBool(1 + Projectile.timeLeft / 32)) - { - BloodParticle p = new(Projectile.Center + Main.rand.NextVector2CircularEdge(32, 32), (-Projectile.velocity).RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 6f, MathHelper.Pi / 6f)) * Main.rand.NextFloat(0.25f, 0.75f), Main.rand.Next(10, 17), 1f, Color.Red); - GeneralParticleHandler.SpawnParticle(p); - } - } - Projectile.velocity = InitialVelocity + AcceleratingVelocity; - Projectile.rotation += RotationSpeed; - } - - public override void SendExtraAI(BinaryWriter writer) - { - writer.WritePackedVector2(InitialVelocity); - writer.WritePackedVector2(AcceleratingVelocity); - } - - public override void ReceiveExtraAI(BinaryReader reader) - { - InitialVelocity = reader.ReadPackedVector2(); - AcceleratingVelocity = reader.ReadPackedVector2(); - } - - public override bool PreDraw(ref Color lightColor) - { - Main.spriteBatch.SetBlendState(BlendState.Additive); - Texture2D tex = TextureAssets.Projectile[Type].Value; - Vector2 drawPos = Projectile.Center - Main.screenPosition; - Color drawColor = Color.Red; - if (!ChildSafety.Disabled) - drawColor = Main.DiscoColor; - - if (CalamityClientConfig.Instance.Afterimages) - { - for (int i = 0; i < Projectile.oldPos.Length; ++i) - { - float afterimageRot = Projectile.oldRot[i]; - drawPos = Projectile.oldPos[i] + (Projectile.Size / 2f) - Main.screenPosition + new Vector2(0f, Projectile.gfxOffY); - if (i != 0) - drawColor *= 0.9f; - - // DO NOT REMOVE THESE "UNNECESSARY" FLOAT CASTS. THIS WILL BREAK THE AFTERIMAGES. - float interpolant = ((float)(Projectile.oldPos.Length - i) / (float)Projectile.oldPos.Length); - Main.spriteBatch.Draw(tex, drawPos, null, drawColor, afterimageRot, tex.Size() * 0.5f, Projectile.scale * interpolant, SpriteEffects.None, 0f); - } - } - //else - // Main.EntitySpriteDraw(tex, drawPos, tex.Frame(), drawColor, Projectile.rotation, tex.Size() * 0.5f, Projectile.scale, SpriteEffects.None, 0); - - Main.spriteBatch.SetBlendState(BlendState.AlphaBlend); - - return false; - } - } - - public class CirclingBloodScythe : ModProjectile, ILocalizedModType - { - public new string LocalizationCategory => "Projectiles.Boss"; - public override string Texture => "CalamityMod/Particles/VerticalSmearRagged"; - - private static float RotationSpeed => MathHelper.Pi / 8f; - private static int Lifetime => BrainOfCthulhuAI.CrimsonEyeAttackDuration; - private static float MaxCircleSpeed => MathHelper.Pi / 30f; //1 rev per second - - ref float CircleAngle => ref Projectile.ai[0]; - ref float CircleRadius => ref Projectile.ai[1]; - ref float CircleRadiusVelocity => ref Projectile.ai[2]; - - public override void SetStaticDefaults() - { - ProjectileID.Sets.TrailCacheLength[Type] = 16; - ProjectileID.Sets.TrailingMode[Type] = 2; - } - - public override void SetDefaults() - { - Projectile.width = 300; - Projectile.height = 300; - Projectile.penetrate = -1; - Projectile.Opacity = 1f; - Projectile.tileCollide = false; - Projectile.timeLeft = Lifetime; - Projectile.damage = 10; - Projectile.scale = 0.1f; - Projectile.hostile = true; - } - - public override void OnSpawn(IEntitySource source) - { - Projectile.rotation = CircleAngle; - for (int i = 0; i < 3; i++) - { - BloodParticle p = new(Projectile.Center, Projectile.velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 6f, MathHelper.Pi / 6f)) * Main.rand.NextFloat(0.5f, 1f), 32, 1f, Color.Red); - GeneralParticleHandler.SpawnParticle(p); - } - BloodParticle2 p2 = new(Projectile.Center, Projectile.velocity * 0.75f, 16, 0.5f, Color.Red); - GeneralParticleHandler.SpawnParticle(p2); - } - - public override void AI() - { - if(NPC.crimsonBoss == -1) - { - Projectile.active = false; - return; - } - int UpTime = Lifetime - Projectile.timeLeft; - - if (UpTime < 30f) - CircleRadius = MathHelper.Lerp(0f, 128f, CalamityUtils.CircOutEasing(UpTime / 30f, 1)); - else if(UpTime < Lifetime - 180) - CircleRadius = 128f; - else - { - if (UpTime == Lifetime - 180) - CircleRadiusVelocity = -3f; - CircleRadius += CircleRadiusVelocity; - CircleRadiusVelocity += 0.1f; - } - - if (UpTime >= 15f) - { - if (UpTime < 30f) - CircleAngle += MathHelper.Lerp(0f, MaxCircleSpeed, CalamityUtils.SineInEasing((UpTime - 15) / 15f, 1)); - else if (UpTime < 870) - CircleAngle += MaxCircleSpeed; - else if (UpTime < 900) - CircleAngle += MathHelper.Lerp(MaxCircleSpeed, MaxCircleSpeed / 3f, CalamityUtils.SineOutEasing((UpTime - 870) / 30f, 1)); - else - CircleAngle += MaxCircleSpeed / 3f; - - if (Main.rand.NextBool(6)) - { - BloodParticle p = new(Projectile.Center + Main.rand.NextVector2CircularEdge(32, 32), (Projectile.DirectionTo(Main.npc[NPC.crimsonBoss].Center).RotatedBy(MathHelper.PiOver2) * 16f).RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 6f, MathHelper.Pi / 6f)) * Main.rand.NextFloat(0.25f, 0.75f), Main.rand.Next(10, 17), 1f, Color.Red); - GeneralParticleHandler.SpawnParticle(p); - } - } - - NPC boss = Main.npc[NPC.crimsonBoss]; - - Projectile.Center = boss.Center + (CircleAngle.ToRotationVector2() * CircleRadius); - Projectile.rotation += RotationSpeed; - } - - public override bool PreDraw(ref Color lightColor) - { - Main.spriteBatch.SetBlendState(BlendState.Additive); - Texture2D tex = TextureAssets.Projectile[Type].Value; - Vector2 drawPos = Projectile.Center - Main.screenPosition; - Color drawColor = Color.Red; - if (!ChildSafety.Disabled) - drawColor = Main.DiscoColor; - - if (CalamityClientConfig.Instance.Afterimages) - { - for (int i = 0; i < Projectile.oldPos.Length; ++i) - { - float afterimageRot = Projectile.oldRot[i]; - drawPos = Projectile.oldPos[i] + (Projectile.Size / 2f) - Main.screenPosition + new Vector2(0f, Projectile.gfxOffY); - if (i != 0) - drawColor *= 0.9f; - // DO NOT REMOVE THESE "UNNECESSARY" FLOAT CASTS. THIS WILL BREAK THE AFTERIMAGES. - float interpolant = ((float)(Projectile.oldPos.Length - i) / (float)Projectile.oldPos.Length); - Main.spriteBatch.Draw(tex, drawPos, null, drawColor, afterimageRot, tex.Size() * 0.5f, Projectile.scale * interpolant, SpriteEffects.None, 0f); - } - } - else - Main.EntitySpriteDraw(tex, drawPos, tex.Frame(), drawColor, Projectile.rotation, tex.Size() * 0.5f, Projectile.scale, SpriteEffects.None, 0); - - Main.spriteBatch.SetBlendState(BlendState.AlphaBlend); - - return false; - } - } - - public class IchorShower : ModProjectile, ILocalizedModType - { - public new string LocalizationCategory => "Projectiles.Boss"; - public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; - - public override void SetDefaults() - { - Projectile.width = 8; - Projectile.height = 8; - Projectile.penetrate = -1; - Projectile.Opacity = 1f; - Projectile.tileCollide = false; - Projectile.timeLeft = 480; - Projectile.damage = 10; - Projectile.scale = 1; - Projectile.hostile = true; - Projectile.extraUpdates = 1; - } - - public override void AI() - { - for(int i = 0; i < 3; i++) - Dust.NewDustPerfect(Projectile.Center + Main.rand.NextVector2Circular(4, 4), DustID.Ichor, Vector2.Zero).noGravity = true; - if(Main.rand.NextBool(8)) - Dust.NewDustPerfect(Projectile.Center + Main.rand.NextVector2Circular(4, 4), DustID.GoldFlame, Vector2.UnitX * Projectile.velocity / 10f, Scale: 0.75f); - Projectile.velocity.Y += 0.075f; - } - - public override void OnHitPlayer(Player target, Player.HurtInfo info) - { - target.AddBuff(BuffID.Ichor, 600); - } - } - - public class CrimsonEye : ModProjectile, ILocalizedModType - { - public new string LocalizationCategory => "Projectiles.Boss"; - public override string Texture => "CalamityMod/NPCs/VanillaNPCAIOverrides/Bosses/CrimsonEye"; - - private ref float Time => ref Projectile.ai[0]; - private ref float DistanceRatio => ref Projectile.ai[1]; - private ref float ExplosionTime => ref Projectile.ai[2]; - - private static float TimeToExplode => 30f; - - public override void SetStaticDefaults() - { - ProjectileID.Sets.DontAttachHideToAlpha[Type] = true; - Main.projFrames[Type] = 5; - } - - public override void SetDefaults() - { - Projectile.width = 100; - Projectile.height = 36; - Projectile.penetrate = -1; - Projectile.Opacity = 1f; - Projectile.tileCollide = false; - Projectile.timeLeft = 300; - Projectile.scale = 1; - Projectile.hostile = false; - Projectile.hide = true; - } - - public override void OnSpawn(IEntitySource source) - { - for (int i = 0; i < 32; i++) - Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.Crimstone); - } - - public override void AI() - { - if (Time > 45) - { - Player closest = Main.player[Player.FindClosest(Projectile.position, Projectile.width, Projectile.height)]; - DistanceRatio = 1 - MathHelper.Clamp((Projectile.Center.Distance(closest.Center) - 128) / 120f, 0f, 1f); - - if (DistanceRatio >= 1 && Projectile.frame == 4) - { - if (Projectile.timeLeft < 120) - Projectile.timeLeft = 120; - - if (ExplosionTime == TimeToExplode) - { - Projectile.hostile = true; - DetailedExplosion explosion = new(Projectile.Center, Vector2.Zero, Color.Orange, Vector2.One, Main.rand.NextFloatDirection(), 0.3f, 0.9f, 24); - GeneralParticleHandler.SpawnParticle(explosion); - - Projectile.Resize(256, 256); - } - else if (Projectile.width == 256) - Projectile.active = false; - - ExplosionTime++; - } - else - { - if (ExplosionTime > 0) - ExplosionTime--; - - if (Projectile.width == 256) - Projectile.active = false; - } - - if (Time > 65) - { - if (Projectile.timeLeft <= 20) - Projectile.frame = (Projectile.timeLeft - 5) / 5; - else - Projectile.frame = 4; - } - else if (Time % 5 == 0) - Projectile.frame++; - } - Time++; - } - - public override void DrawBehind(int index, List behindNPCsAndTiles, List behindNPCs, List behindProjectiles, List overPlayers, List overWiresUI) - { - behindNPCsAndTiles.Add(index); - } - - public override bool PreDraw(ref Color lightColor) - { - if (ExplosionTime >= TimeToExplode) - return false; - - if (ExplosionTime > 0) - { - float ratio = ExplosionTime / TimeToExplode; - - Vector3 lightLevels = lightColor.ToVector3(); - float lightLevel = (lightLevels.X + lightLevels.Y + lightLevels.Z) / 3f; - lightColor = Color.Lerp(lightColor, Color.Lerp(Color.Red, Color.Gold, (float)Math.Sin(ExplosionTime / 4f) / 2f + 0.5f) * lightLevel, ratio); - lightColor.A = 255; - } - - return true; - } - - public override void PostDraw(Color lightColor) - { - if (ExplosionTime >= TimeToExplode) - return; - - float ratio = CalamityUtils.SineOutEasing(ExplosionTime / TimeToExplode, 1); - - if (Projectile.frame == 4) - { - Texture2D tex = ModContent.Request(Texture + "Pupil").Value; - Vector2 rangeScale = new Vector2(2.25f, 0.75f); - Vector2 dir = Projectile.DirectionTo(Main.LocalPlayer.Center); - if(ExplosionTime > 0) - { - if (ratio < 0.25f) - dir = Vector2.Lerp(dir, Vector2.Zero, ratio * 4f); - else - dir = Main.rand.NextVector2CircularEdge(1, 1); - } - - if (Projectile.timeLeft <= 50) - dir *= (Projectile.timeLeft - 20) / 30f; - - float range = 6f; - if (ratio > 0.25f) - { - range = MathHelper.Lerp(0f, 6f, (ratio - 0.25f) * 0.75f); - } - else if (Time < 85) - { - float lerp = CalamityUtils.SineOutEasing((Time - 65) / 20f, 1); - range = MathHelper.Lerp(0f, range, lerp); - } - - Main.EntitySpriteDraw(tex, Projectile.Center + (dir * rangeScale * range) - Main.screenPosition, null, lightColor, 0, tex.Size() * 0.5f, 1f, 0); - } - - if (DistanceRatio > 0) - { - /* - Main.spriteBatch.SetBlendState(BlendState.Additive); - - Texture2D tex = ModContent.Request("CalamityMod/Particles/HollowCircleHardEdge").Value; - Color color = Color.Red * DistanceRatio; - if (Time <= 65) - color *= (Time - 45) / 20f; - - if (Projectile.timeLeft <= 20) - color *= Projectile.timeLeft / 20f; - - Main.EntitySpriteDraw(tex, Projectile.Center - Main.screenPosition, null, color, 0f, tex.Size() * 0.5f, 1.75f, 0); - - Main.spriteBatch.SetBlendState(BlendState.AlphaBlend); - */ - - float opacity = DistanceRatio; - if (Time <= 65) - opacity *= (Time - 45) / 20f; - - if (Projectile.timeLeft <= 20) - opacity *= Projectile.timeLeft / 20f; - - Main.spriteBatch.EnterShaderRegion(); - Texture2D telegraphBase = ModContent.Request("CalamityMod/Projectiles/InvisibleProj").Value; - - GameShaders.Misc["CalamityMod:CircularAoETelegraph"].UseOpacity(opacity); - GameShaders.Misc["CalamityMod:CircularAoETelegraph"].UseColor(Color.Lerp(Color.Red, Color.OrangeRed, 0.7f * (float)Math.Pow(0.5 + 0.5 * Math.Sin(Main.GlobalTimeWrappedHourly), 3))); - GameShaders.Misc["CalamityMod:CircularAoETelegraph"].UseSecondaryColor(Color.Lerp(Color.Yellow, Color.White, 0.5f)); - GameShaders.Misc["CalamityMod:CircularAoETelegraph"].UseSaturation(ratio * 0.5f + 0.5f); - - GameShaders.Misc["CalamityMod:CircularAoETelegraph"].Apply(); - - Vector2 drawPosition = Projectile.Center - Main.screenPosition; - Main.EntitySpriteDraw(telegraphBase, drawPosition, null, lightColor, 0, telegraphBase.Size() / 2f, 248f, 0, 0); - Main.spriteBatch.ExitShaderRegion(); - } - } - } - - public class TelekineticEnemyGrab : ModProjectile, ILocalizedModType - { - public new string LocalizationCategory => "Projectiles.Boss"; - public override string Texture => "CalamityMod/Particles/BloomRing"; - - BezierCurve curve; - int throwSign = 0; - Vector2 throwPos = Vector2.Zero; - Vector2 holdPos; - - ref float Time => ref Projectile.ai[0]; - ref float StunTime => ref Projectile.ai[1]; - - private static Dictionary EnemyGlowTextures = []; - int enemyID { get => (int)Projectile.ai[2]; set => Projectile.ai[2] = (float)value; } - - public override void SetDefaults() - { - Projectile.width = 48; - Projectile.height = 48; - Projectile.penetrate = -1; - Projectile.Opacity = 1f; - Projectile.tileCollide = false; - Projectile.timeLeft = 1200; - Projectile.damage = 10; - Projectile.hostile = true; - } - - public override void OnSpawn(IEntitySource source) - { - holdPos = new Vector2(Projectile.Center.X, Main.npc[NPC.crimsonBoss].Center.Y - 128) - Main.npc[NPC.crimsonBoss].Center; - - Projectile.rotation = Main.rand.NextFloat(0, MathHelper.TwoPi); - - StunTime = -1; - - enemyID = Main.rand.Next(0, 3); - int[] enemyIDs = [NPCID.FaceMonster, NPCID.Crimera, NPCID.BloodCrawler]; - enemyID = enemyIDs[enemyID]; - - Projectile.netUpdate = true; - } - - public override void AI() - { - if(NPC.crimsonBoss == -1) - { - Projectile.active = false; - return; - } - - if (Time <= 90) - Projectile.hostile = false; - else - Projectile.hostile = true; - - bool throwing = Time > 180; - float throwTime = Time - 180; - if (throwing) - { - if (throwSign == 0) - throwSign = Math.Sign(Projectile.Center.X - Main.npc[NPC.crimsonBoss].Center.X) * -Math.Sign(Main.player[Main.npc[NPC.crimsonBoss].target].Center.Y - Main.npc[NPC.crimsonBoss].Center.Y); - } - bool thrown = throwTime > 90; - - if (!thrown) - { - Vector2 startPoint = Main.npc[NPC.crimsonBoss].Center;// Main.npc[NPC.crimsonBoss].Center; - Vector2 endPoint = Projectile.Center; - - if (StunTime == -1) - { - if (!throwing) - { - if (Time >= 150) - Projectile.velocity = ((holdPos + Main.npc[NPC.crimsonBoss].Center) - Projectile.Center) / 30f; - else if (Time != 0) - { - - if (Time <= 90) - { - if (Time == 90) - Projectile.velocity = Vector2.UnitY * -24f; - if (Time % 30 == 0) - Projectile.velocity = Vector2.UnitY * -16f; - else - Projectile.velocity *= 0.33f; - } - else - Projectile.velocity *= 0.966f; - } - } - else - { - if (throwTime <= 30) - throwPos = (Projectile.Center + Projectile.velocity) - (Main.npc[NPC.crimsonBoss].Center + Main.npc[NPC.crimsonBoss].velocity); - Vector2 target = Main.player[Main.npc[NPC.crimsonBoss].target].Center; - Vector2 throwDir = (target - (throwPos + (Main.npc[NPC.crimsonBoss].Center + Main.npc[NPC.crimsonBoss].velocity))).SafeNormalize(Vector2.UnitY); - - if (throwTime >= 30 && throwTime <= 90) - { - if (throwTime <= 60f) - { - Projectile.Center = Vector2.Lerp(throwPos, throwPos - throwDir * 56f, CalamityUtils.SineInOutEasing((throwTime - 30) / 30f, 1)) + (Main.npc[NPC.crimsonBoss].Center + Main.npc[NPC.crimsonBoss].velocity); - Projectile.velocity = Vector2.Zero; - } - else - { - Projectile.velocity += throwDir * 0.9f; - if (throwTime == 90) - { - float dist = Projectile.Center.Distance(target) / 2f; - dist /= Projectile.velocity.Length(); - Projectile.velocity.Y -= dist * 0.6f; - Projectile.tileCollide = true; - } - } - } - } - } - - Vector2 direction = endPoint - startPoint; - float distance = Vector2.Distance(startPoint, endPoint); - - float lerp = CalamityUtils.SineInOutEasing(MathHelper.Clamp((throwTime) / 60f, 0f, 1f), 1); - float xMult = MathHelper.Lerp(-Math.Clamp(direction.X / 256f, -1, 1), throwSign, lerp); - float yMult = Math.Clamp(direction.Y / 256f, -1, 1); - float curveIntensity = Math.Clamp(distance / 420f, 0f, 0.66f) * xMult * yMult; - //Main.NewText("Completion: " + lerp + ", Intensity: " + curveIntensity); - Vector2 perpindicular = direction.RotatedBy(MathHelper.PiOver2); - - Vector2 controlPoint1 = startPoint + (direction * 0.25f) + (perpindicular * curveIntensity); - Vector2 controlPoint2 = startPoint + (direction * 0.75f) + (perpindicular * curveIntensity); - - curve = new BezierCurve(startPoint, controlPoint1, controlPoint2, endPoint); - } - else - { - Projectile.velocity.Y += 0.6f; - } - - if (StunTime >= 0) - { - if (StunTime < 30f) - StunTime++; - else - { - Projectile.velocity.Y += 0.6f; - Projectile.tileCollide = true; - } - } - else - { - if (Time > 90) - Projectile.rotation += (Projectile.velocity.X / 100f) - (Math.Sign(Main.npc[NPC.crimsonBoss].Center.X - Projectile.Center.X) * 0.025f); - Time++; - } - } - - public override void SendExtraAI(BinaryWriter writer) - { - writer.Write(throwSign); - - writer.WritePackedVector2(throwPos); - - writer.WritePackedVector2(holdPos); - } - - public override void ReceiveExtraAI(BinaryReader reader) - { - throwSign = reader.ReadInt32(); - - throwPos = reader.ReadPackedVector2(); - - holdPos = reader.ReadPackedVector2(); - } - - public override bool OnTileCollide(Vector2 oldVelocity) - { - Vector2 velocity = Projectile.velocity.RotatedBy(MathHelper.Pi) / 8f; - Vector2 pos = Projectile.Center; - - switch (enemyID) - { - case NPCID.FaceMonster: - Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver4, MathHelper.PiOver4)), 237); - - for (int i = 0; i < 24; i++) - Dust.NewDustPerfect(pos + Main.rand.NextVector2Circular(16, 32), DustID.Blood, Scale: Main.rand.NextFloat(1, 2)); - - SoundEngine.PlaySound(SoundID.NPCDeath1 with { Volume = 0.25f }, pos); - break; - case NPCID.Crimera: - Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver4, MathHelper.PiOver4)), 223); - Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver2, MathHelper.PiOver2)), 224); - - for (int i = 0; i < 24; i++) - Dust.NewDustPerfect(pos + Main.rand.NextVector2Circular(16, 32), DustID.Blood, Scale: Main.rand.NextFloat(1, 2)); - - SoundEngine.PlaySound(SoundID.NPCDeath1 with { Volume = 0.25f }, pos); - break; - case NPCID.BloodCrawler: - Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver4, MathHelper.PiOver4)), 351); - Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver2, MathHelper.PiOver2)), 352); - Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver2, MathHelper.PiOver2)), 353); - - for (int i = 0; i < 24; i++) - Dust.NewDustPerfect(pos + Main.rand.NextVector2Circular(16, 32), DustID.Blood, Scale: Main.rand.NextFloat(1, 2)); - - SoundEngine.PlaySound(SoundID.NPCDeath1 with { Volume = 0.25f }, pos); - break; - default: - Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver4, MathHelper.PiOver4)), 42); - Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver2, MathHelper.PiOver2)), 43); - Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver2, MathHelper.PiOver2)), 44); - - SoundEngine.PlaySound(SoundID.NPCDeath2 with { Volume = 0.175f }, pos); - break; - } - - return true; - } - - bool evenRed = false; - public override bool PreDraw(ref Color lightColor) - { - //Handles getting the glow textures - if (EnemyGlowTextures.Count == 0 || !EnemyGlowTextures.ContainsKey(enemyID)) - { - EnemyGlowTextures.Clear(); - int[] enemyIDs = [NPCID.FaceMonster, NPCID.Crimera, NPCID.BloodCrawler]; - foreach (int id in enemyIDs) - { - var baseTex = TextureAssets.Npc[id]; - var glow = new Texture2D(Main.graphics.GraphicsDevice, baseTex.Value.Width, baseTex.Value.Height); - - var BaseArray = new Color[glow.Width * glow.Height]; - var ColorArray = new Color[glow.Width * glow.Height]; - baseTex.Value.GetData(BaseArray); - for (var i = 0; i < BaseArray.Length; i++) - { - if (BaseArray[i].A != 0) - ColorArray[i] = new Color(255, 255, 255); - } - glow.SetData(ColorArray); - - EnemyGlowTextures.Add(id, glow); - } - } - - int type = enemyID; - int frameCount; - int wrapFrame = -1; - int startFrame = 0; - float mult = 0.75f; - - switch(type) - { - case NPCID.FaceMonster: - frameCount = 16; - startFrame = 2; - wrapFrame = 16; - break; - case NPCID.Crimera: - frameCount = 2; - mult = 0.25f; - break; - case NPCID.BloodCrawler: - frameCount = 5; - mult = 0.25f; - break; - default: - frameCount = 15; - type = NPCID.Skeleton; - startFrame = 1; - break; - } - - if (wrapFrame == -1) - wrapFrame = frameCount; - - Texture2D tex = TextureAssets.Npc[type].Value; - - int currentFrame = ((int)((1200 - Projectile.timeLeft) * mult)) % (wrapFrame - startFrame); - - Rectangle frame = tex.Frame(1, frameCount, 0, startFrame + currentFrame); - - float throwTime = Time - 180; - - float opacity = 1f; - if (Time < 10) - opacity = Time / 10f; - - if (throwTime <= 90) - { - int pCount = 12; - - float wrapTime = 60; - float wrappedTime = MathHelper.Clamp((Time % (wrapTime + 1)) / wrapTime, 0f, 1f); - if (wrappedTime == 0) - evenRed = !evenRed; - - float glowOpacity = MathHelper.Clamp(1 - ((throwTime - 75) / 15f), 0f, 1f); - if (StunTime >= 0) - glowOpacity = 1 - (StunTime / 30f); - if (Time < 15) - glowOpacity = Time / 15f; - - Main.spriteBatch.End(out var snapshot); - Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullNone, null, Main.GameViewMatrix.TransformationMatrix); - - Texture2D ring = TextureAssets.Projectile[Type].Value; - - List points = curve.GetPoints(pCount); - for (int i = 1; i < pCount; i++) - { - float scale1 = MathHelper.Lerp(0.1f, 1f, i / (float)(pCount - 1)); - float scale2 = MathHelper.Lerp(0.1f, 1f, (i + 1) / (float)(pCount - 1)); - float scale = MathHelper.Lerp(scale1, scale2, wrappedTime); - - float rot1 = (points[i] - points[i - 1]).ToRotation(); - - float rot2; - if (i == pCount - 1) - rot2 = points[i].ToRotation(); - else - rot2 = (points[i + 1] - points[i]).ToRotation(); - - float rot; - if (i == pCount - 1) - rot = rot1; - else - rot = rot1.AngleLerp(rot2, wrappedTime); - - Vector2 pos; - if (i == pCount - 1) - pos = Vector2.Lerp(points[i], points[i] + rot.ToRotationVector2() * Vector2.Distance(points[^1], points[^2]), wrappedTime); - else - pos = Vector2.Lerp(points[i], points[i + 1], wrappedTime); - - Color color; - if (evenRed) - color = (i % 2 == 0 ? Color.Red : Color.Magenta) * 0.666f; - else - color = (i % 2 == 0 ? Color.Magenta : Color.Red) * 0.666f; - - if (i == pCount - 1) - color *= 1 - wrappedTime; - else if (i == 1) - color *= wrappedTime; - - Main.spriteBatch.Draw(ring, pos + Projectile.velocity - Main.screenPosition, null, color * glowOpacity, rot, ring.Size() * 0.5f, new Vector2(0.5f, 1f) * scale, 0, 0); - } - - Main.spriteBatch.End(); - Main.spriteBatch.Begin(snapshot); - - Vector2[] offsets = [Vector2.UnitX * 2, Vector2.UnitX * -2, Vector2.UnitY * 2, Vector2.UnitY * -2]; - for(int i = 0; i < 4; i++) - Main.EntitySpriteDraw(EnemyGlowTextures[enemyID], Projectile.Center - Main.screenPosition + offsets[i].RotatedBy(Projectile.rotation), frame, Color.Lerp(Color.Red, Color.Magenta, ((float)Math.Sin((Main.GlobalTimeWrappedHourly * 5f)) / 2f + 0.5f)) * glowOpacity, Projectile.rotation, frame.Size() * 0.5f, 1f, 0); - } - - Main.EntitySpriteDraw(tex, Projectile.Center - Main.screenPosition, frame, lightColor * opacity, Projectile.rotation, frame.Size() * 0.5f, 1f, 0); - - return false; - } - } - - public class TelekineticBlast : ModProjectile, ILocalizedModType - { - public new string LocalizationCategory => "Projectiles.Boss"; - public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; - - public override void SetDefaults() - { - Projectile.width = 1; - Projectile.height = 1; - Projectile.penetrate = -1; - Projectile.Opacity = 1f; - Projectile.tileCollide = false; - Projectile.timeLeft = 1; - Projectile.damage = 0; - Projectile.scale = 1; - Projectile.hostile = true; - } - - Player target => Main.player[(int)Projectile.ai[0]]; - float debuffMultiplier => Projectile.ai[1]; - - public override void OnSpawn(IEntitySource source) - { - for (int i = 0; i < 6; i++) - { - Vector2 dir = target.Center - Projectile.Center; - int lifeTime = 24; - dir /= lifeTime / 2f * 5f; - dir *= i; - DirectionalPulseRing pulse = new(Projectile.Center, dir, i % 2 == 0 ? Color.Red : Color.Orange, new Vector2(0.5f, 1), dir.ToRotation(), 0f, i / 5f, lifeTime + 8); - GeneralParticleHandler.SpawnParticle(pulse); - } - - SoundEngine.PlaySound(SoundID.Zombie105, Projectile.Center); //LC Laugh - target.AddBuff(BuffID.Darkness, (int)Math.Round(900 * debuffMultiplier)); - target.AddBuff(BuffID.Bleeding, (int)Math.Round(900 * debuffMultiplier)); - target.AddBuff(BuffID.Confused, (int)Math.Round(60 * debuffMultiplier)); - int timeToAdd = (int)Math.Round(600 * debuffMultiplier); - int bbIndex = target.buffType.ToList().IndexOf(ModContent.BuffType()); - if (bbIndex != -1) - timeToAdd += target.buffTime[bbIndex]; - target.AddBuff(ModContent.BuffType(), timeToAdd); - - target.Calamity().adrenaline = 0; - } - } -} diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs index ee16e8e2e2..44d52c8a76 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,67 @@ 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() + { + if (Main.gameMenu) + return; + + 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(); @@ -235,7 +300,7 @@ namespace CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses if (NPC.velocity.Y == 0f && NPC.velocity.X == 0f && useShadowHandAttack) { NPC.velocity.X = 0f; - NPC.ai[0] = 5f; + NPC.ai[0] = targetData.Center.Y < NPC.Center.Y - 50f ? 5f : 3f; NPC.ai[1] = 0f; NPC.localAI[1] = 0f; calamityGlobalNPC.newAI[0] -= 1f; diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/WallOfFleshAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/WallOfFleshAI.cs index 98f99514cd..0dca2a085f 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/WallOfFleshAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/WallOfFleshAI.cs @@ -511,30 +511,6 @@ namespace CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses return false; } - public override void PostDraw(Mod mod, SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) - { - // Laser telegraph - bool enraged = NPC.localAI[3] > 0f; - float eyeTelegraphGateValue = LaserShootGateValue - LaserShootTelegraphTime; - if (NPC.localAI[1] > eyeTelegraphGateValue || NPC.localAI[2] > 0f || enraged) - { - Texture2D glowTexture = CalamityClientConfig.Instance.EnableVanillaTextureEdits ? ExtraTextureRefs.WallOfFleshEyeGlowmask.Value : TextureAssets.Npc[NPC.type].Value; - var halfSize = NPC.frame.Size() / 2; - SpriteEffects spriteEffects = NPC.spriteDirection == 1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None; - - float colorScale = enraged ? MathHelper.Clamp(NPC.localAI[3] / EnragedLaserFiringDuration, 0f, 1f) : - NPC.localAI[2] > 0f ? 1f - ((NPC.localAI[2] - 1f) / TotalLasersPerBarrage) : - MathHelper.Clamp((NPC.localAI[1] - eyeTelegraphGateValue) / LaserShootTelegraphTime, 0f, 1f); - - Color drawColor2 = new Color(100, 0, 200, 192) * colorScale; - for (int i = 0; i < 2; i++) - { - spriteBatch.Draw(glowTexture, NPC.Center - screenPos + new Vector2(0, NPC.gfxOffY), NPC.frame, - drawColor2, NPC.rotation, halfSize, NPC.scale, spriteEffects, 0f); - } - } - } - public class HungryAI : VanillaAIOverride { public override bool AI(Mod mod) @@ -908,6 +884,30 @@ namespace CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses return false; } + + public override void PostDraw(Mod mod, SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) + { + // Laser telegraph + bool enraged = NPC.localAI[3] > 0f; + float eyeTelegraphGateValue = LaserShootGateValue - LaserShootTelegraphTime; + if (NPC.localAI[1] > eyeTelegraphGateValue || NPC.localAI[2] > 0f || enraged) + { + Texture2D glowTexture = CalamityClientConfig.Instance.EnableVanillaTextureEdits ? ExtraTextureRefs.WallOfFleshEyeGlowmask.Value : TextureAssets.Npc[NPC.type].Value; + var halfSize = NPC.frame.Size() / 2; + SpriteEffects spriteEffects = NPC.spriteDirection == 1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None; + + float colorScale = enraged ? MathHelper.Clamp(NPC.localAI[3] / EnragedLaserFiringDuration, 0f, 1f) : + NPC.localAI[2] > 0f ? 1f - ((NPC.localAI[2] - 1f) / TotalLasersPerBarrage) : + MathHelper.Clamp((NPC.localAI[1] - eyeTelegraphGateValue) / LaserShootTelegraphTime, 0f, 1f); + + Color drawColor2 = new Color(100, 0, 200, 192) * colorScale; + for (int i = 0; i < 2; i++) + { + spriteBatch.Draw(glowTexture, NPC.Center - screenPos + new Vector2(0, NPC.gfxOffY), NPC.frame, + drawColor2, NPC.rotation, halfSize, NPC.scale, spriteEffects, 0f); + } + } + } } } } diff --git a/NPCs/VanillaNPCAIOverrides/RegularEnemies/RevengeanceAndDeaths/FlyingAI.cs b/NPCs/VanillaNPCAIOverrides/RegularEnemies/RevengeanceAndDeaths/FlyingAI.cs index 9dd39b20b9..1c582877aa 100644 --- a/NPCs/VanillaNPCAIOverrides/RegularEnemies/RevengeanceAndDeaths/FlyingAI.cs +++ b/NPCs/VanillaNPCAIOverrides/RegularEnemies/RevengeanceAndDeaths/FlyingAI.cs @@ -269,9 +269,9 @@ public static partial class RevengeanceAndDeathAI } if (targetData.Center.X - NPC.Center.X > 0f) - NPC.spriteDirection = -1; - else NPC.spriteDirection = 1; + else + NPC.spriteDirection = -1; NPC.rotation = NPC.velocity.X * 0.1f; diff --git a/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs b/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs index f3317441c4..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 { @@ -12,17 +11,23 @@ namespace CalamityMod.NPCs.VanillaNPCAIOverrides { public NPC NPC { get; set; } 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) { } diff --git a/Packets/StartDialogueDisplayPacket.cs b/Packets/StartDialogueDisplayPacket.cs new file mode 100644 index 0000000000..a96cbdd738 --- /dev/null +++ b/Packets/StartDialogueDisplayPacket.cs @@ -0,0 +1,118 @@ +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 : byte + { + 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.Write((byte)type); + 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 + + string name = packet.ReadString(); + packet.ReadFlags(out bool progressDialogue, out bool hasEntity); + + int entity = -1; + Vector2 pos = Vector2.zeroVector; + EntityType type = EntityType.NPC; + if (hasEntity) + { + type = (EntityType)packet.ReadByte(); + entity = packet.ReadInt32(); + } + else + pos = packet.ReadPackedVector2(); + + int index = packet.ReadInt32(); + int uptime = packet.ReadInt32(); + byte effect = packet.ReadByte(); + float wrapWidth = packet.ReadSingle(); + + if (Main.netMode != NetmodeID.MultiplayerClient) + return; + + DisplayEffect de = GetEffect((DisplayEffectID)effect); + + if (hasEntity) + { + 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); + + } + } + +} diff --git a/Particles/BossRoar.cs b/Particles/BossRoar.cs new file mode 100644 index 0000000000..2ce1b63234 --- /dev/null +++ b/Particles/BossRoar.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.ModLoader; + +namespace CalamityMod.Particles; + +public class BossRoar : Particle +{ + public override string Texture => "CalamityMod/Particles/RoarPulse"; + public override bool SetLifetime => true; + public override bool UseCustomDraw => true; + + private float OriginalScale; + private float FinalScale; + private float BaseOpacity; + private float opacity; + private Color BaseColor; + + public BossRoar(Vector2 position, Color color, float rotation, float originalScale, float finalScale, int lifeTime, float baseOpacity = 1f) + { + Position = position; + BaseColor = color; + OriginalScale = originalScale; + FinalScale = finalScale; + Scale = originalScale; + Lifetime = lifeTime; + BaseOpacity = baseOpacity; + Rotation = rotation; + } + + public override void Update() + { + Scale = MathHelper.Lerp(OriginalScale, FinalScale, LifetimeCompletion); + + opacity = 1f; + if (LifetimeCompletion < 0.1f) + opacity = MathHelper.Lerp(0f, 1f, LifetimeCompletion * 10); + + Color = BaseColor * opacity; + } + + public override void CustomDraw(SpriteBatch spriteBatch) + { + Texture2D tex = ModContent.Request(Texture).Value; + spriteBatch.Draw(tex, Position - Main.screenPosition, null, Color * BaseOpacity, Rotation, tex.Size() / 2f, Scale, SpriteEffects.None, 0); + } +} diff --git a/Particles/BrainOfCthulhuAfterImage.cs b/Particles/BrainOfCthulhuAfterImage.cs new file mode 100644 index 0000000000..f1b18b1eaf --- /dev/null +++ b/Particles/BrainOfCthulhuAfterImage.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.DataStructures; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.GameContent; +using Terraria.ID; + +namespace CalamityMod.Particles; + +public class BrainOfCthulhuAfterImage : Particle +{ + public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; + + public override bool UseCustomDraw => false; + + public override bool SetLifetime => true; + + public override bool Important => true; + + private float StartFade; + private float Opacity = 1f; + List Path; + private Vector2 MyScale = Vector2.One; + private Rectangle Frame; + + public BrainOfCthulhuAfterImage(BezierCurve path, float rotation, Vector2 scale, int lifeTime, Rectangle frame, float startFadeRatio = 0f) + { + Path = path.GetPoints(lifeTime); + Position = Path[0]; + Rotation = rotation; + StartFade = startFadeRatio; + MyScale = scale; + Frame = frame; + Lifetime = lifeTime + 1; + } + + public override void Update() + { + float timeRatio = Time / (float)Lifetime; + Opacity = timeRatio; + if (StartFade != 0f) + Opacity = Utils.GetLerpValue(StartFade, 1f, timeRatio, true); + + Opacity = 1 - CalamityUtils.SineInEasing(Opacity, 1); + + List pathPosition = Path; + + if (Time >= pathPosition.Count) + { + Kill(); + return; + } + + Position = pathPosition[Time]; + } + + public override void CustomDraw(SpriteBatch spriteBatch) + { + float timeRatio = Time / (float)Lifetime; + spriteBatch.Draw(TextureAssets.Npc[NPCID.BrainofCthulhu].Value, Position - Main.screenPosition, Frame, Lighting.GetColor(Position.ToTileCoordinates()) * Opacity * 0.5f, Rotation, Frame.Size() * 0.5f, MyScale, 0, 0); + } +} + diff --git a/Particles/BrokenTendril.cs b/Particles/BrokenTendril.cs new file mode 100644 index 0000000000..6a91a187a7 --- /dev/null +++ b/Particles/BrokenTendril.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses.BrainOfCthulhu; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.ID; + +namespace CalamityMod.Particles; + +public class BrokenTendril : Particle +{ + public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; + + public override bool UseCustomDraw => true; + + private int TimeLeft; + private float Opacity = 1f; + private Vector2 InitalScale = Vector2.One; + + public BrokenTendril(Vector2 position, Vector2 velocity, float rotation, Vector2 scale, int lifeTime) + { + Position = position; + Velocity = velocity; + Scale = 1f; + Rotation = rotation; + TimeLeft = lifeTime; + InitalScale = scale - Vector2.One; + } + + public override void Update() + { + if (InitalScale != Vector2.Zero) + { + InitalScale *= 0.98f; + if (InitalScale.X < 0.05f) + InitalScale.X = 0; + if (InitalScale.Y < 0.05f) + InitalScale.Y = 0; + } + + Point tilePos = Position.ToTileCoordinates(); + if (!WorldGen.InWorld(tilePos.X, tilePos.Y)) + { + Kill(); + return; + } + + if (Main.tile[tilePos].IsTileSolid() || TileID.Sets.Platforms[Main.tile[tilePos].TileType]) + { + Velocity.Y = 0; + if (Velocity.X > 0.05f) + Velocity.X *= 0.9f; + else + Velocity.X = 0; + } + else + { + Velocity.Y += 0.25f; + Velocity.X *= 0.975f; + } + + Rotation += Velocity.X * 0.025f; + + if (Velocity == Vector2.Zero) + { + if (TimeLeft < 30) + { + Opacity = TimeLeft / 30f; + if (TimeLeft <= 0) + Kill(); + } + TimeLeft--; + } + } + + public override void CustomDraw(SpriteBatch spriteBatch) + { + Texture2D tex = BrainOfCthulhuSystem.tendril.Value; + float rot = Rotation - MathHelper.PiOver2; + Vector2 center = Position + rot.ToRotationVector2() * tex.Size().Y * InitalScale.Y * 0.5f; + spriteBatch.Draw(tex, Position - Main.screenPosition, null, Lighting.GetColor(center.ToTileCoordinates()) * Opacity, rot, tex.Size() * Vector2.UnitX * 0.5f, Vector2.One + InitalScale, SpriteEffects.None, 0f); + } +} + diff --git a/Particles/DeathAshParticle.cs b/Particles/DeathAshParticle.cs index f600b156ca..98d0553b5d 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]; @@ -65,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) @@ -91,7 +91,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/Projectiles/Boss/BrainOfCthulhu/BloodScythe.cs b/Projectiles/Boss/BrainOfCthulhu/BloodScythe.cs new file mode 100644 index 0000000000..2a05b796be --- /dev/null +++ b/Projectiles/Boss/BrainOfCthulhu/BloodScythe.cs @@ -0,0 +1,242 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses.BrainOfCthulhu; +using CalamityMod.Particles; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.DataStructures; +using Terraria.GameContent; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Boss.BrainOfCthulhu; + +public class BloodScythe : ModProjectile, ILocalizedModType +{ + public new string LocalizationCategory => "Projectiles.Boss"; + public override string Texture => "CalamityMod/Particles/VerticalSmearRagged"; + + private Vector2 InitialVelocity = Vector2.Zero; + private Vector2 AcceleratingVelocity = Vector2.Zero; + private static float RotationSpeed => MathHelper.Pi / 8f; + private static float Acceleration => 0.175f; + private static int Lifetime => 240; + + public override void SetStaticDefaults() + { + ProjectileID.Sets.TrailCacheLength[Type] = 16; + ProjectileID.Sets.TrailingMode[Type] = 2; + } + + public override void SetDefaults() + { + Projectile.width = 300; + Projectile.height = 300; + Projectile.penetrate = -1; + Projectile.Opacity = 1f; + Projectile.tileCollide = false; + Projectile.timeLeft = Lifetime; + Projectile.damage = 10; + Projectile.scale = 0.1f; + Projectile.hostile = true; + } + + public override void OnSpawn(IEntitySource source) + { + InitialVelocity = Projectile.velocity; + Projectile.rotation = Projectile.velocity.ToRotation(); + for (int i = 0; i < 3; i++) + { + BloodParticle p = new(Projectile.Center, Projectile.velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 6f, MathHelper.Pi / 6f)) * Main.rand.NextFloat(0.5f, 1f), 32, 1f, Color.Red); + GeneralParticleHandler.SpawnParticle(p); + } + BloodParticle2 p2 = new(Projectile.Center, Projectile.velocity * 0.75f, 16, 0.5f, Color.Red); + GeneralParticleHandler.SpawnParticle(p2); + } + + public override void AI() + { + int UpTime = Lifetime - Projectile.timeLeft; + InitialVelocity *= 0.925f; + if (UpTime > 15) + { + AcceleratingVelocity += Projectile.velocity.SafeNormalize(InitialVelocity.SafeNormalize(Vector2.UnitX)) * Acceleration; + if (Main.rand.NextBool(1 + Projectile.timeLeft / 32)) + { + BloodParticle p = new(Projectile.Center + Main.rand.NextVector2CircularEdge(32, 32), (-Projectile.velocity).RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 6f, MathHelper.Pi / 6f)) * Main.rand.NextFloat(0.25f, 0.75f), Main.rand.Next(10, 17), 1f, Color.Red); + GeneralParticleHandler.SpawnParticle(p); + } + } + Projectile.velocity = InitialVelocity + AcceleratingVelocity; + Projectile.rotation += RotationSpeed; + } + + public override void SendExtraAI(BinaryWriter writer) + { + writer.WritePackedVector2(InitialVelocity); + writer.WritePackedVector2(AcceleratingVelocity); + } + + public override void ReceiveExtraAI(BinaryReader reader) + { + InitialVelocity = reader.ReadPackedVector2(); + AcceleratingVelocity = reader.ReadPackedVector2(); + } + + public override bool PreDraw(ref Color lightColor) + { + Main.spriteBatch.SetBlendState(BlendState.Additive); + Texture2D tex = TextureAssets.Projectile[Type].Value; + Vector2 drawPos = Projectile.Center - Main.screenPosition; + Color drawColor = Color.Red; + if (!ChildSafety.Disabled) + drawColor = Main.DiscoColor; + + if (CalamityClientConfig.Instance.Afterimages) + { + for (int i = 0; i < Projectile.oldPos.Length; ++i) + { + float afterimageRot = Projectile.oldRot[i]; + drawPos = Projectile.oldPos[i] + (Projectile.Size / 2f) - Main.screenPosition + new Vector2(0f, Projectile.gfxOffY); + if (i != 0) + drawColor *= 0.9f; + + // DO NOT REMOVE THESE "UNNECESSARY" FLOAT CASTS. THIS WILL BREAK THE AFTERIMAGES. + float interpolant = ((float)(Projectile.oldPos.Length - i) / (float)Projectile.oldPos.Length); + Main.spriteBatch.Draw(tex, drawPos, null, drawColor, afterimageRot, tex.Size() * 0.5f, Projectile.scale * interpolant, SpriteEffects.None, 0f); + } + } + //else + // Main.EntitySpriteDraw(tex, drawPos, tex.Frame(), drawColor, Projectile.rotation, tex.Size() * 0.5f, Projectile.scale, SpriteEffects.None, 0); + + Main.spriteBatch.SetBlendState(BlendState.AlphaBlend); + + return false; + } +} + +public class CirclingBloodScythe : ModProjectile, ILocalizedModType +{ + public new string LocalizationCategory => "Projectiles.Boss"; + public override string Texture => "CalamityMod/Particles/VerticalSmearRagged"; + + private static float RotationSpeed => MathHelper.Pi / 8f; + private static int Lifetime => BrainOfCthulhuAI.CrimsonEyeAttackDuration; + private static float MaxCircleSpeed => MathHelper.Pi / 30f; //1 rev per second + + ref float CircleAngle => ref Projectile.ai[0]; + ref float CircleRadius => ref Projectile.ai[1]; + ref float CircleRadiusVelocity => ref Projectile.ai[2]; + + public override void SetStaticDefaults() + { + ProjectileID.Sets.TrailCacheLength[Type] = 16; + ProjectileID.Sets.TrailingMode[Type] = 2; + } + + public override void SetDefaults() + { + Projectile.width = 300; + Projectile.height = 300; + Projectile.penetrate = -1; + Projectile.Opacity = 1f; + Projectile.tileCollide = false; + Projectile.timeLeft = Lifetime; + Projectile.damage = 10; + Projectile.scale = 0.1f; + Projectile.hostile = true; + } + + public override void OnSpawn(IEntitySource source) + { + Projectile.rotation = CircleAngle; + for (int i = 0; i < 3; i++) + { + BloodParticle p = new(Projectile.Center, Projectile.velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 6f, MathHelper.Pi / 6f)) * Main.rand.NextFloat(0.5f, 1f), 32, 1f, Color.Red); + GeneralParticleHandler.SpawnParticle(p); + } + BloodParticle2 p2 = new(Projectile.Center, Projectile.velocity * 0.75f, 16, 0.5f, Color.Red); + GeneralParticleHandler.SpawnParticle(p2); + } + + public override void AI() + { + if (NPC.crimsonBoss == -1) + { + Projectile.active = false; + return; + } + int UpTime = Lifetime - Projectile.timeLeft; + + if (UpTime < 30f) + CircleRadius = MathHelper.Lerp(0f, 128f, CalamityUtils.CircOutEasing(UpTime / 30f, 1)); + else if (UpTime < Lifetime - 180) + CircleRadius = 128f; + else + { + if (UpTime == Lifetime - 180) + CircleRadiusVelocity = -3f; + CircleRadius += CircleRadiusVelocity; + CircleRadiusVelocity += 0.1f; + } + + if (UpTime >= 15f) + { + if (UpTime < 30f) + CircleAngle += MathHelper.Lerp(0f, MaxCircleSpeed, CalamityUtils.SineInEasing((UpTime - 15) / 15f, 1)); + else if (UpTime < 870) + CircleAngle += MaxCircleSpeed; + else if (UpTime < 900) + CircleAngle += MathHelper.Lerp(MaxCircleSpeed, MaxCircleSpeed / 3f, CalamityUtils.SineOutEasing((UpTime - 870) / 30f, 1)); + else + CircleAngle += MaxCircleSpeed / 3f; + + if (Main.rand.NextBool(6)) + { + BloodParticle p = new(Projectile.Center + Main.rand.NextVector2CircularEdge(32, 32), (Projectile.DirectionTo(Main.npc[NPC.crimsonBoss].Center).RotatedBy(MathHelper.PiOver2) * 16f).RotatedBy(Main.rand.NextFloat(-MathHelper.Pi / 6f, MathHelper.Pi / 6f)) * Main.rand.NextFloat(0.25f, 0.75f), Main.rand.Next(10, 17), 1f, Color.Red); + GeneralParticleHandler.SpawnParticle(p); + } + } + + NPC boss = Main.npc[NPC.crimsonBoss]; + + Projectile.Center = boss.Center + (CircleAngle.ToRotationVector2() * CircleRadius); + Projectile.rotation += RotationSpeed; + } + + public override bool PreDraw(ref Color lightColor) + { + Main.spriteBatch.SetBlendState(BlendState.Additive); + Texture2D tex = TextureAssets.Projectile[Type].Value; + Vector2 drawPos = Projectile.Center - Main.screenPosition; + Color drawColor = Color.Red; + if (!ChildSafety.Disabled) + drawColor = Main.DiscoColor; + + if (CalamityClientConfig.Instance.Afterimages) + { + for (int i = 0; i < Projectile.oldPos.Length; ++i) + { + float afterimageRot = Projectile.oldRot[i]; + drawPos = Projectile.oldPos[i] + (Projectile.Size / 2f) - Main.screenPosition + new Vector2(0f, Projectile.gfxOffY); + if (i != 0) + drawColor *= 0.9f; + // DO NOT REMOVE THESE "UNNECESSARY" FLOAT CASTS. THIS WILL BREAK THE AFTERIMAGES. + float interpolant = ((float)(Projectile.oldPos.Length - i) / (float)Projectile.oldPos.Length); + Main.spriteBatch.Draw(tex, drawPos, null, drawColor, afterimageRot, tex.Size() * 0.5f, Projectile.scale * interpolant, SpriteEffects.None, 0f); + } + } + else + Main.EntitySpriteDraw(tex, drawPos, tex.Frame(), drawColor, Projectile.rotation, tex.Size() * 0.5f, Projectile.scale, SpriteEffects.None, 0); + + Main.spriteBatch.SetBlendState(BlendState.AlphaBlend); + + return false; + } +} + diff --git a/Projectiles/Boss/BrainOfCthulhu/CrimsonEye.cs b/Projectiles/Boss/BrainOfCthulhu/CrimsonEye.cs new file mode 100644 index 0000000000..59747e4788 --- /dev/null +++ b/Projectiles/Boss/BrainOfCthulhu/CrimsonEye.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Particles; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.DataStructures; +using Terraria.Graphics.Shaders; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Boss.BrainOfCthulhu; + +public class CrimsonEye : ModProjectile, ILocalizedModType +{ + public new string LocalizationCategory => "Projectiles.Boss"; + + private ref float Time => ref Projectile.ai[0]; + private ref float DistanceRatio => ref Projectile.ai[1]; + private ref float ExplosionTime => ref Projectile.ai[2]; + + private static float TimeToExplode => 30f; + + public override void SetStaticDefaults() + { + ProjectileID.Sets.DontAttachHideToAlpha[Type] = true; + Main.projFrames[Type] = 5; + } + + public override void SetDefaults() + { + Projectile.width = 100; + Projectile.height = 36; + Projectile.penetrate = -1; + Projectile.Opacity = 1f; + Projectile.tileCollide = false; + Projectile.timeLeft = 300; + Projectile.scale = 1; + Projectile.hostile = false; + Projectile.hide = true; + } + + public override void OnSpawn(IEntitySource source) + { + for (int i = 0; i < 32; i++) + Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.Crimstone); + } + + public override void AI() + { + if (Time > 45) + { + Player closest = Main.player[Player.FindClosest(Projectile.position, Projectile.width, Projectile.height)]; + DistanceRatio = 1 - MathHelper.Clamp((Projectile.Center.Distance(closest.Center) - 128) / 120f, 0f, 1f); + + if (DistanceRatio >= 1 && Projectile.frame == 4) + { + if (Projectile.timeLeft < 120) + Projectile.timeLeft = 120; + + if (ExplosionTime == TimeToExplode) + { + Projectile.hostile = true; + DetailedExplosion explosion = new(Projectile.Center, Vector2.Zero, Color.Orange, Vector2.One, Main.rand.NextFloatDirection(), 0.3f, 0.9f, 24); + GeneralParticleHandler.SpawnParticle(explosion); + + Projectile.Resize(256, 256); + } + else if (Projectile.width == 256) + Projectile.active = false; + + ExplosionTime++; + } + else + { + if (ExplosionTime > 0) + ExplosionTime--; + + if (Projectile.width == 256) + Projectile.active = false; + } + + if (Time > 65) + { + if (Projectile.timeLeft <= 20) + Projectile.frame = (Projectile.timeLeft - 5) / 5; + else + Projectile.frame = 4; + } + else if (Time % 5 == 0) + Projectile.frame++; + } + Time++; + } + + public override void DrawBehind(int index, List behindNPCsAndTiles, List behindNPCs, List behindProjectiles, List overPlayers, List overWiresUI) + { + behindNPCsAndTiles.Add(index); + } + + public override bool PreDraw(ref Color lightColor) + { + if (ExplosionTime >= TimeToExplode) + return false; + + if (ExplosionTime > 0) + { + float ratio = ExplosionTime / TimeToExplode; + + Vector3 lightLevels = lightColor.ToVector3(); + float lightLevel = (lightLevels.X + lightLevels.Y + lightLevels.Z) / 3f; + lightColor = Color.Lerp(lightColor, Color.Lerp(Color.Red, Color.Gold, (float)Math.Sin(ExplosionTime / 4f) / 2f + 0.5f) * lightLevel, ratio); + lightColor.A = 255; + } + + return true; + } + + public override void PostDraw(Color lightColor) + { + if (ExplosionTime >= TimeToExplode) + return; + + float ratio = CalamityUtils.SineOutEasing(ExplosionTime / TimeToExplode, 1); + + if (Projectile.frame == 4) + { + Texture2D tex = ModContent.Request(Texture + "Pupil").Value; + Vector2 rangeScale = new Vector2(2.25f, 0.75f); + Vector2 dir = Projectile.DirectionTo(Main.LocalPlayer.Center); + if (ExplosionTime > 0) + { + if (ratio < 0.25f) + dir = Vector2.Lerp(dir, Vector2.Zero, ratio * 4f); + else + dir = Main.rand.NextVector2CircularEdge(1, 1); + } + + if (Projectile.timeLeft <= 50) + dir *= (Projectile.timeLeft - 20) / 30f; + + float range = 6f; + if (ratio > 0.25f) + { + range = MathHelper.Lerp(0f, 6f, (ratio - 0.25f) * 0.75f); + } + else if (Time < 85) + { + float lerp = CalamityUtils.SineOutEasing((Time - 65) / 20f, 1); + range = MathHelper.Lerp(0f, range, lerp); + } + + Main.EntitySpriteDraw(tex, Projectile.Center + (dir * rangeScale * range) - Main.screenPosition, null, lightColor, 0, tex.Size() * 0.5f, 1f, 0); + } + + if (DistanceRatio > 0) + { + /* + Main.spriteBatch.SetBlendState(BlendState.Additive); + + Texture2D tex = ModContent.Request("CalamityMod/Particles/HollowCircleHardEdge").Value; + Color color = Color.Red * DistanceRatio; + if (Time <= 65) + color *= (Time - 45) / 20f; + + if (Projectile.timeLeft <= 20) + color *= Projectile.timeLeft / 20f; + + Main.EntitySpriteDraw(tex, Projectile.Center - Main.screenPosition, null, color, 0f, tex.Size() * 0.5f, 1.75f, 0); + + Main.spriteBatch.SetBlendState(BlendState.AlphaBlend); + */ + + float opacity = DistanceRatio; + if (Time <= 65) + opacity *= (Time - 45) / 20f; + + if (Projectile.timeLeft <= 20) + opacity *= Projectile.timeLeft / 20f; + + Main.spriteBatch.EnterShaderRegion(); + Texture2D telegraphBase = ModContent.Request("CalamityMod/Projectiles/InvisibleProj").Value; + + GameShaders.Misc["CalamityMod:CircularAoETelegraph"].UseOpacity(opacity); + GameShaders.Misc["CalamityMod:CircularAoETelegraph"].UseColor(Color.Lerp(Color.Red, Color.OrangeRed, 0.7f * (float)Math.Pow(0.5 + 0.5 * Math.Sin(Main.GlobalTimeWrappedHourly), 3))); + GameShaders.Misc["CalamityMod:CircularAoETelegraph"].UseSecondaryColor(Color.Lerp(Color.Yellow, Color.White, 0.5f)); + GameShaders.Misc["CalamityMod:CircularAoETelegraph"].UseSaturation(ratio * 0.5f + 0.5f); + + GameShaders.Misc["CalamityMod:CircularAoETelegraph"].Apply(); + + Vector2 drawPosition = Projectile.Center - Main.screenPosition; + Main.EntitySpriteDraw(telegraphBase, drawPosition, null, lightColor, 0, telegraphBase.Size() / 2f, 248f, 0, 0); + Main.spriteBatch.ExitShaderRegion(); + } + } +} + diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/CrimsonEye.png b/Projectiles/Boss/BrainOfCthulhu/CrimsonEye.png similarity index 100% rename from NPCs/VanillaNPCAIOverrides/Bosses/CrimsonEye.png rename to Projectiles/Boss/BrainOfCthulhu/CrimsonEye.png diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/CrimsonEyePupil.png b/Projectiles/Boss/BrainOfCthulhu/CrimsonEyePupil.png similarity index 100% rename from NPCs/VanillaNPCAIOverrides/Bosses/CrimsonEyePupil.png rename to Projectiles/Boss/BrainOfCthulhu/CrimsonEyePupil.png diff --git a/Projectiles/Boss/BrainOfCthulhu/IchorShower.cs b/Projectiles/Boss/BrainOfCthulhu/IchorShower.cs new file mode 100644 index 0000000000..0af2bbb0ae --- /dev/null +++ b/Projectiles/Boss/BrainOfCthulhu/IchorShower.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Boss.BrainOfCthulhu; + +public class IchorShower : ModProjectile, ILocalizedModType +{ + public new string LocalizationCategory => "Projectiles.Boss"; + public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; + + public override void SetDefaults() + { + Projectile.width = 8; + Projectile.height = 8; + Projectile.penetrate = -1; + Projectile.Opacity = 1f; + Projectile.tileCollide = false; + Projectile.timeLeft = 480; + Projectile.damage = 10; + Projectile.scale = 1; + Projectile.hostile = true; + Projectile.extraUpdates = 1; + } + + public override void AI() + { + for (int i = 0; i < 3; i++) + Dust.NewDustPerfect(Projectile.Center + Main.rand.NextVector2Circular(4, 4), DustID.Ichor, Vector2.Zero).noGravity = true; + if (Main.rand.NextBool(8)) + Dust.NewDustPerfect(Projectile.Center + Main.rand.NextVector2Circular(4, 4), DustID.GoldFlame, Vector2.UnitX * Projectile.velocity / 10f, Scale: 0.75f); + Projectile.velocity.Y += 0.075f; + } + + public override void OnHitPlayer(Player target, Player.HurtInfo info) + { + target.AddBuff(BuffID.Ichor, 600); + } +} + diff --git a/Projectiles/Boss/BrainOfCthulhu/TelekineticBlast.cs b/Projectiles/Boss/BrainOfCthulhu/TelekineticBlast.cs new file mode 100644 index 0000000000..a9e49f9be7 --- /dev/null +++ b/Projectiles/Boss/BrainOfCthulhu/TelekineticBlast.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Particles; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.Audio; +using Terraria.DataStructures; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Boss.BrainOfCthulhu; + +public class TelekineticBlast : ModProjectile, ILocalizedModType +{ + public new string LocalizationCategory => "Projectiles.Boss"; + public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; + + public override void SetDefaults() + { + Projectile.width = 1; + Projectile.height = 1; + Projectile.penetrate = -1; + Projectile.Opacity = 1f; + Projectile.tileCollide = false; + Projectile.timeLeft = 1; + Projectile.damage = 0; + Projectile.scale = 1; + Projectile.hostile = true; + } + + Player target => Main.player[(int)Projectile.ai[0]]; + float debuffMultiplier => Projectile.ai[1]; + + public override void OnSpawn(IEntitySource source) + { + for (int i = 0; i < 6; i++) + { + Vector2 dir = target.Center - Projectile.Center; + int lifeTime = 24; + dir /= lifeTime / 2f * 5f; + dir *= i; + DirectionalPulseRing pulse = new(Projectile.Center, dir, i % 2 == 0 ? Color.Red : Color.Orange, new Vector2(0.5f, 1), dir.ToRotation(), 0f, i / 5f, lifeTime + 8); + GeneralParticleHandler.SpawnParticle(pulse); + } + + SoundEngine.PlaySound(SoundID.Zombie105, Projectile.Center); //LC Laugh + target.AddBuff(BuffID.Darkness, (int)Math.Round(900 * debuffMultiplier)); + target.AddBuff(BuffID.Bleeding, (int)Math.Round(900 * debuffMultiplier)); + target.AddBuff(BuffID.Confused, (int)Math.Round(60 * debuffMultiplier)); + int timeToAdd = (int)Math.Round(600 * debuffMultiplier); + int bbIndex = target.buffType.ToList().IndexOf(ModContent.BuffType()); + if (bbIndex != -1) + timeToAdd += target.buffTime[bbIndex]; + target.AddBuff(ModContent.BuffType(), timeToAdd); + + target.Calamity().adrenaline = 0; + } +} diff --git a/Projectiles/Boss/BrainOfCthulhu/TelekineticEnemyGrab.cs b/Projectiles/Boss/BrainOfCthulhu/TelekineticEnemyGrab.cs new file mode 100644 index 0000000000..7c69c9d96e --- /dev/null +++ b/Projectiles/Boss/BrainOfCthulhu/TelekineticEnemyGrab.cs @@ -0,0 +1,387 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.DataStructures; +using CalamityMod.Utilities.Daybreak; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.Audio; +using Terraria.DataStructures; +using Terraria.GameContent; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Boss.BrainOfCthulhu; + +public class TelekineticEnemyGrab : ModProjectile, ILocalizedModType +{ + public new string LocalizationCategory => "Projectiles.Boss"; + public override string Texture => "CalamityMod/Particles/BloomRing"; + + BezierCurve curve; + int throwSign = 0; + Vector2 throwPos = Vector2.Zero; + Vector2 holdPos; + + ref float Time => ref Projectile.ai[0]; + ref float StunTime => ref Projectile.ai[1]; + + private static Dictionary EnemyGlowTextures = []; + int enemyID { get => (int)Projectile.ai[2]; set => Projectile.ai[2] = (float)value; } + + public override void SetDefaults() + { + Projectile.width = 48; + Projectile.height = 48; + Projectile.penetrate = -1; + Projectile.Opacity = 1f; + Projectile.tileCollide = false; + Projectile.timeLeft = 1200; + Projectile.damage = 10; + Projectile.hostile = true; + } + + public override void OnSpawn(IEntitySource source) + { + holdPos = new Vector2(Projectile.Center.X, Main.npc[NPC.crimsonBoss].Center.Y - 128) - Main.npc[NPC.crimsonBoss].Center; + + Projectile.rotation = Main.rand.NextFloat(0, MathHelper.TwoPi); + + StunTime = -1; + + enemyID = Main.rand.Next(0, 3); + int[] enemyIDs = [NPCID.FaceMonster, NPCID.Crimera, NPCID.BloodCrawler]; + enemyID = enemyIDs[enemyID]; + + Projectile.netUpdate = true; + } + + public override void AI() + { + if (NPC.crimsonBoss == -1) + { + Projectile.active = false; + return; + } + + if (Time <= 90) + Projectile.hostile = false; + else + Projectile.hostile = true; + + bool throwing = Time > 180; + float throwTime = Time - 180; + if (throwing) + { + if (throwSign == 0) + throwSign = Math.Sign(Projectile.Center.X - Main.npc[NPC.crimsonBoss].Center.X) * -Math.Sign(Main.player[Main.npc[NPC.crimsonBoss].target].Center.Y - Main.npc[NPC.crimsonBoss].Center.Y); + } + bool thrown = throwTime > 90; + + if (!thrown) + { + Vector2 startPoint = Main.npc[NPC.crimsonBoss].Center;// Main.npc[NPC.crimsonBoss].Center; + Vector2 endPoint = Projectile.Center; + + if (StunTime == -1) + { + if (!throwing) + { + if (Time >= 150) + Projectile.velocity = ((holdPos + Main.npc[NPC.crimsonBoss].Center) - Projectile.Center) / 30f; + else if (Time != 0) + { + + if (Time <= 90) + { + if (Time == 90) + Projectile.velocity = Vector2.UnitY * -24f; + if (Time % 30 == 0) + Projectile.velocity = Vector2.UnitY * -16f; + else + Projectile.velocity *= 0.33f; + } + else + Projectile.velocity *= 0.966f; + } + } + else + { + if (throwTime <= 30) + throwPos = (Projectile.Center + Projectile.velocity) - (Main.npc[NPC.crimsonBoss].Center + Main.npc[NPC.crimsonBoss].velocity); + Vector2 target = Main.player[Main.npc[NPC.crimsonBoss].target].Center; + Vector2 throwDir = (target - (throwPos + (Main.npc[NPC.crimsonBoss].Center + Main.npc[NPC.crimsonBoss].velocity))).SafeNormalize(Vector2.UnitY); + + if (throwTime >= 30 && throwTime <= 90) + { + if (throwTime <= 60f) + { + Projectile.Center = Vector2.Lerp(throwPos, throwPos - throwDir * 56f, CalamityUtils.SineInOutEasing((throwTime - 30) / 30f, 1)) + (Main.npc[NPC.crimsonBoss].Center + Main.npc[NPC.crimsonBoss].velocity); + Projectile.velocity = Vector2.Zero; + } + else + { + Projectile.velocity += throwDir * 0.9f; + if (throwTime == 90) + { + float dist = Projectile.Center.Distance(target) / 2f; + dist /= Projectile.velocity.Length(); + Projectile.velocity.Y -= dist * 0.6f; + Projectile.tileCollide = true; + } + } + } + } + } + + Vector2 direction = endPoint - startPoint; + float distance = Vector2.Distance(startPoint, endPoint); + + float lerp = CalamityUtils.SineInOutEasing(MathHelper.Clamp((throwTime) / 60f, 0f, 1f), 1); + float xMult = MathHelper.Lerp(-Math.Clamp(direction.X / 256f, -1, 1), throwSign, lerp); + float yMult = Math.Clamp(direction.Y / 256f, -1, 1); + float curveIntensity = Math.Clamp(distance / 420f, 0f, 0.66f) * xMult * yMult; + //Main.NewText("Completion: " + lerp + ", Intensity: " + curveIntensity); + Vector2 perpindicular = direction.RotatedBy(MathHelper.PiOver2); + + Vector2 controlPoint1 = startPoint + (direction * 0.25f) + (perpindicular * curveIntensity); + Vector2 controlPoint2 = startPoint + (direction * 0.75f) + (perpindicular * curveIntensity); + + curve = new BezierCurve(startPoint, controlPoint1, controlPoint2, endPoint); + } + else + { + Projectile.velocity.Y += 0.6f; + } + + if (StunTime >= 0) + { + if (StunTime < 30f) + StunTime++; + else + { + Projectile.velocity.Y += 0.6f; + Projectile.tileCollide = true; + } + } + else + { + if (Time > 90) + Projectile.rotation += (Projectile.velocity.X / 100f) - (Math.Sign(Main.npc[NPC.crimsonBoss].Center.X - Projectile.Center.X) * 0.025f); + Time++; + } + } + + public override void SendExtraAI(BinaryWriter writer) + { + writer.Write(throwSign); + + writer.WriteVector2(throwPos); + + writer.WriteVector2(holdPos); + } + + public override void ReceiveExtraAI(BinaryReader reader) + { + throwSign = reader.ReadInt32(); + + throwPos = reader.ReadVector2(); + + holdPos = reader.ReadVector2(); + } + + 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 + Projectile.velocity; + + switch (enemyID) + { + case NPCID.FaceMonster: + Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver4, MathHelper.PiOver4)), 237); + + for (int i = 0; i < 24; i++) + Dust.NewDustPerfect(pos + Main.rand.NextVector2Circular(16, 32), DustID.Blood, Scale: Main.rand.NextFloat(1, 2)); + + SoundEngine.PlaySound(SoundID.NPCDeath1 with { Volume = 0.25f }, pos); + break; + case NPCID.Crimera: + Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver4, MathHelper.PiOver4)), 223); + Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver2, MathHelper.PiOver2)), 224); + + for (int i = 0; i < 24; i++) + Dust.NewDustPerfect(pos + Main.rand.NextVector2Circular(16, 32), DustID.Blood, Scale: Main.rand.NextFloat(1, 2)); + + SoundEngine.PlaySound(SoundID.NPCDeath1 with { Volume = 0.25f }, pos); + break; + case NPCID.BloodCrawler: + Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver4, MathHelper.PiOver4)), 351); + Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver2, MathHelper.PiOver2)), 352); + Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver2, MathHelper.PiOver2)), 353); + + for (int i = 0; i < 24; i++) + Dust.NewDustPerfect(pos + Main.rand.NextVector2Circular(16, 32), DustID.Blood, Scale: Main.rand.NextFloat(1, 2)); + + SoundEngine.PlaySound(SoundID.NPCDeath1 with { Volume = 0.25f }, pos); + break; + default: + Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver4, MathHelper.PiOver4)), 42); + Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver2, MathHelper.PiOver2)), 43); + Gore.NewGore(Projectile.GetSource_Death(), pos - (Projectile.velocity / 2f), velocity.RotatedBy(Main.rand.NextFloat(-MathHelper.PiOver2, MathHelper.PiOver2)), 44); + + SoundEngine.PlaySound(SoundID.NPCDeath2 with { Volume = 0.175f }, pos); + break; + } + } + + bool evenRed = false; + public override bool PreDraw(ref Color lightColor) + { + //Handles getting the glow textures + if (EnemyGlowTextures.Count == 0 || !EnemyGlowTextures.ContainsKey(enemyID)) + { + EnemyGlowTextures.Clear(); + int[] enemyIDs = [NPCID.FaceMonster, NPCID.Crimera, NPCID.BloodCrawler]; + foreach (int id in enemyIDs) + { + var baseTex = TextureAssets.Npc[id]; + var glow = new Texture2D(Main.graphics.GraphicsDevice, baseTex.Value.Width, baseTex.Value.Height); + + var BaseArray = new Color[glow.Width * glow.Height]; + var ColorArray = new Color[glow.Width * glow.Height]; + baseTex.Value.GetData(BaseArray); + for (var i = 0; i < BaseArray.Length; i++) + { + if (BaseArray[i].A != 0) + ColorArray[i] = new Color(255, 255, 255); + } + glow.SetData(ColorArray); + + EnemyGlowTextures.Add(id, glow); + } + } + + int type = enemyID; + int frameCount; + int wrapFrame = -1; + int startFrame = 0; + float mult = 0.75f; + + switch (type) + { + case NPCID.FaceMonster: + frameCount = 16; + startFrame = 2; + wrapFrame = 16; + break; + case NPCID.Crimera: + frameCount = 2; + mult = 0.25f; + break; + case NPCID.BloodCrawler: + frameCount = 5; + mult = 0.25f; + break; + default: + frameCount = 15; + type = NPCID.Skeleton; + startFrame = 1; + break; + } + + if (wrapFrame == -1) + wrapFrame = frameCount; + + Texture2D tex = TextureAssets.Npc[type].Value; + + int currentFrame = ((int)((1200 - Projectile.timeLeft) * mult)) % (wrapFrame - startFrame); + + Rectangle frame = tex.Frame(1, frameCount, 0, startFrame + currentFrame); + + float throwTime = Time - 180; + + float opacity = 1f; + if (Time < 10) + opacity = Time / 10f; + + if (throwTime <= 90) + { + int pCount = 12; + + float wrapTime = 60; + float wrappedTime = MathHelper.Clamp((Time % (wrapTime + 1)) / wrapTime, 0f, 1f); + if (wrappedTime == 0) + evenRed = !evenRed; + + float glowOpacity = MathHelper.Clamp(1 - ((throwTime - 75) / 15f), 0f, 1f); + if (StunTime >= 0) + glowOpacity = 1 - (StunTime / 30f); + if (Time < 15) + glowOpacity = Time / 15f; + + Main.spriteBatch.End(out var snapshot); + Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullNone, null, Main.GameViewMatrix.TransformationMatrix); + + Texture2D ring = TextureAssets.Projectile[Type].Value; + + List points = curve.GetPoints(pCount); + for (int i = 1; i < pCount; i++) + { + float scale1 = MathHelper.Lerp(0.1f, 1f, i / (float)(pCount - 1)); + float scale2 = MathHelper.Lerp(0.1f, 1f, (i + 1) / (float)(pCount - 1)); + float scale = MathHelper.Lerp(scale1, scale2, wrappedTime); + + float rot1 = (points[i] - points[i - 1]).ToRotation(); + + float rot2; + if (i == pCount - 1) + rot2 = points[i].ToRotation(); + else + rot2 = (points[i + 1] - points[i]).ToRotation(); + + float rot; + if (i == pCount - 1) + rot = rot1; + else + rot = rot1.AngleLerp(rot2, wrappedTime); + + Vector2 pos; + if (i == pCount - 1) + pos = Vector2.Lerp(points[i], points[i] + rot.ToRotationVector2() * Vector2.Distance(points[^1], points[^2]), wrappedTime); + else + pos = Vector2.Lerp(points[i], points[i + 1], wrappedTime); + + Color color; + if (evenRed) + color = (i % 2 == 0 ? Color.Red : Color.Magenta) * 0.666f; + else + color = (i % 2 == 0 ? Color.Magenta : Color.Red) * 0.666f; + + if (i == pCount - 1) + color *= 1 - wrappedTime; + else if (i == 1) + color *= wrappedTime; + + Main.spriteBatch.Draw(ring, pos + Projectile.velocity - Main.screenPosition, null, color * glowOpacity, rot, ring.Size() * 0.5f, new Vector2(0.5f, 1f) * scale, 0, 0); + } + + Main.spriteBatch.End(); + Main.spriteBatch.Begin(snapshot); + + Vector2[] offsets = [Vector2.UnitX * 2, Vector2.UnitX * -2, Vector2.UnitY * 2, Vector2.UnitY * -2]; + for (int i = 0; i < 4; i++) + Main.EntitySpriteDraw(EnemyGlowTextures[enemyID], Projectile.Center - Main.screenPosition + offsets[i].RotatedBy(Projectile.rotation), frame, Color.Lerp(Color.Red, Color.Magenta, ((float)Math.Sin((Main.GlobalTimeWrappedHourly * 5f)) / 2f + 0.5f)) * glowOpacity, Projectile.rotation, frame.Size() * 0.5f, 1f, 0); + } + + Main.EntitySpriteDraw(tex, Projectile.Center - Main.screenPosition, frame, lightColor * opacity, Projectile.rotation, frame.Size() * 0.5f, 1f, 0); + + return false; + } +} + diff --git a/Projectiles/Boss/BrimstoneBarrage.cs b/Projectiles/Boss/BrimstoneBarrage.cs index 163d5fdc32..2ebd4d4fcf 100644 --- a/Projectiles/Boss/BrimstoneBarrage.cs +++ b/Projectiles/Boss/BrimstoneBarrage.cs @@ -137,7 +137,7 @@ namespace CalamityMod.Projectiles.Boss } } - CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Type], lightColor * 0.5f, 1); + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Type], lightColor, 1); return false; } public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, 10 * Projectile.scale, targetHitbox); diff --git a/Projectiles/CalamityGlobalProjectile.cs b/Projectiles/CalamityGlobalProjectile.cs index 32c6305f5b..6dee0c35ee 100644 --- a/Projectiles/CalamityGlobalProjectile.cs +++ b/Projectiles/CalamityGlobalProjectile.cs @@ -4553,8 +4553,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) 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/Magic/CosmicTentacle.cs b/Projectiles/Magic/CosmicTentacle.cs index 0f1d058286..f246aaf0d4 100644 --- a/Projectiles/Magic/CosmicTentacle.cs +++ b/Projectiles/Magic/CosmicTentacle.cs @@ -83,11 +83,11 @@ namespace CalamityMod.Projectiles.Magic scaling = Utils.GetLerpValue(0, scalingTimerMax, scalingTimer, true); float sharpScaling = Utils.GetLerpValue(scalingTimerMax * 0.7f, scalingTimerMax, scalingTimer, true); - if (targetDist < 1400f) + if (targetDist < 1400f && Projectile.timeLeft % 2 == 0) { Particle spark = new CustomSpark(Projectile.Center, -Projectile.velocity * 0.05f, "CalamityMod/Particles/GlowSpark2", false, 12, 0.07f * scaling, Color.Black * 0.85f, new Vector2(1.7f - (1 - sharpScaling), 0.9f + (1 - sharpScaling) * 2), false); GeneralParticleHandler.SpawnParticle(spark); - Particle spark2 = new CustomSpark(Projectile.Center, -Projectile.velocity * 0.05f, "CalamityMod/Particles/GlowSpark", false, 12, 0.035f * scaling, Color.LightGreen * 0.55f, new Vector2(1.7f - (1 - sharpScaling), 0.9f + (1 - sharpScaling) * 2)); + Particle spark2 = new CustomSpark(Projectile.Center, -Projectile.velocity * 0.05f, "CalamityMod/Particles/GlowSpark", false, 12, 0.035f * scaling, Color.LightGreen * 0.75f, new Vector2(1.7f - (1 - sharpScaling), 0.9f + (1 - sharpScaling) * 2)); GeneralParticleHandler.SpawnParticle(spark2); } if (Main.rand.NextBool(6)) diff --git a/Projectiles/Magic/Sandstream.cs b/Projectiles/Magic/Sandstream.cs index 55452152ab..da69d2f40d 100644 --- a/Projectiles/Magic/Sandstream.cs +++ b/Projectiles/Magic/Sandstream.cs @@ -107,7 +107,7 @@ namespace CalamityMod.Projectiles.Magic float rot = MathHelper.ToRadians(i * rotFactor); Vector2 offset = new Vector2(Main.rand.NextFloat(0.5f, 1.5f), 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 9.1f)); Vector2 velOffset = new Vector2(Main.rand.NextFloat(0.5f, 1.5f), 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 9.1f)); - Dust dust = Dust.NewDustPerfect(target.Center + offset, Main.rand.NextBool(3) ? 288 : 121, new Vector2(velOffset.X, velOffset.Y)); + Dust dust = Dust.NewDustPerfect(target.Center + offset, Main.rand.NextBool(3) ? 288 : 207, new Vector2(velOffset.X, velOffset.Y)); dust.noGravity = false; dust.velocity = velOffset; dust.scale = Main.rand.NextFloat(0.5f, 0.8f); @@ -125,7 +125,7 @@ namespace CalamityMod.Projectiles.Magic Vector2 velOffset = new Vector2(Main.rand.NextFloat(1.5f, 5.5f), 0).RotatedBy(rot * Main.rand.NextFloat(3.1f, 9.1f)); MediumMistParticle SandCloud = new MediumMistParticle(Projectile.Center + offset, velOffset * Main.rand.NextFloat(1.5f, 3f), Color.Peru, Color.PeachPuff, Main.rand.NextFloat(0.9f, 1.2f), 160f, Main.rand.NextFloat(0.03f, -0.03f)); GeneralParticleHandler.SpawnParticle(SandCloud); - Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, Main.rand.NextBool() ? 288 : 121, new Vector2(velOffset.X, velOffset.Y)); + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, Main.rand.NextBool() ? 288 : 207, new Vector2(velOffset.X, velOffset.Y)); dust.noGravity = false; dust.velocity = velOffset; dust.scale = Main.rand.NextFloat(1.2f, 1.6f); diff --git a/Projectiles/Melee/SaharaSlicersBlade.png b/Projectiles/Melee/SaharaSlicersBlade.png index d3667f574b..abf539a5d6 100644 Binary files a/Projectiles/Melee/SaharaSlicersBlade.png and b/Projectiles/Melee/SaharaSlicersBlade.png differ diff --git a/Projectiles/Melee/SaharaSlicersBladeAlt.png b/Projectiles/Melee/SaharaSlicersBladeAlt.png index 69a74d3ac1..989f6b5acf 100644 Binary files a/Projectiles/Melee/SaharaSlicersBladeAlt.png and b/Projectiles/Melee/SaharaSlicersBladeAlt.png differ diff --git a/Projectiles/Melee/SaharaSlicersBolt.cs b/Projectiles/Melee/SaharaSlicersBolt.cs index 6628ec23f1..073c587c70 100644 --- a/Projectiles/Melee/SaharaSlicersBolt.cs +++ b/Projectiles/Melee/SaharaSlicersBolt.cs @@ -79,7 +79,7 @@ namespace CalamityMod.Projectiles.Melee Dust dust = Dust.NewDustPerfect(Projectile.Center, Main.rand.NextBool() ? 288 : 121, Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(15f)) * Main.rand.NextFloat(0.3f, 1.9f)); dust.noGravity = false; dust.scale = Main.rand.NextFloat(0.6f, 0.9f); - Dust dust2 = Dust.NewDustPerfect(Projectile.Center, Main.rand.NextBool() ? 288 : 121, Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(35f)) * Main.rand.NextFloat(0.05f, 0.9f)); + Dust dust2 = Dust.NewDustPerfect(Projectile.Center, Main.rand.NextBool() ? 288 : 207, Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(35f)) * Main.rand.NextFloat(0.05f, 0.9f)); dust2.noGravity = false; dust2.scale = Main.rand.NextFloat(0.6f, 0.9f); } @@ -91,10 +91,10 @@ namespace CalamityMod.Projectiles.Melee SoundEngine.PlaySound(SoundID.Item10, Projectile.position); for (int i = 0; i <= 5; i++) { - Dust dust = Dust.NewDustPerfect(Projectile.Center, Main.rand.NextBool() ? 216 : 121, -Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(15f)) * Main.rand.NextFloat(0.2f, 1f)); + Dust dust = Dust.NewDustPerfect(Projectile.Center, Main.rand.NextBool() ? 216 : 207, -Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(15f)) * Main.rand.NextFloat(0.2f, 1f)); dust.noGravity = true; dust.scale = Main.rand.NextFloat(1.1f, 1.8f); - Dust dust2 = Dust.NewDustPerfect(Projectile.Center, Main.rand.NextBool() ? 216 : 121, -Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(35f)) * Main.rand.NextFloat(0.05f, 0.4f)); + Dust dust2 = Dust.NewDustPerfect(Projectile.Center, Main.rand.NextBool() ? 216 : 207, -Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(35f)) * Main.rand.NextFloat(0.05f, 0.4f)); dust2.noGravity = true; dust2.scale = Main.rand.NextFloat(1.1f, 1.8f); } diff --git a/Projectiles/Melee/SaharaSlicersBolt.png b/Projectiles/Melee/SaharaSlicersBolt.png index 7bcc8d6378..9c954972d8 100644 Binary files a/Projectiles/Melee/SaharaSlicersBolt.png and b/Projectiles/Melee/SaharaSlicersBolt.png differ 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; diff --git a/Projectiles/Melee/Shortswords/SaharaSlicersBlade.cs b/Projectiles/Melee/Shortswords/SaharaSlicersBlade.cs index e58b244d1a..247efad73c 100644 --- a/Projectiles/Melee/Shortswords/SaharaSlicersBlade.cs +++ b/Projectiles/Melee/Shortswords/SaharaSlicersBlade.cs @@ -34,8 +34,8 @@ namespace CalamityMod.Projectiles.Melee.Shortswords public override void SetVisualOffsets() { - const int HalfSpriteWidth = 40 / 2; - const int HalfSpriteHeight = 40 / 2; + const int HalfSpriteWidth = 32 / 2; + const int HalfSpriteHeight = 32 / 2; int HalfProjWidth = Projectile.width / 2; int HalfProjHeight = Projectile.height / 2; @@ -82,7 +82,7 @@ namespace CalamityMod.Projectiles.Melee.Shortswords float rot = MathHelper.ToRadians(i * rotFactor); Vector2 offset = new Vector2(Main.rand.NextFloat(0.5f, 2.5f), 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 9.1f)); Vector2 velOffset = new Vector2(Main.rand.NextFloat(0.5f, 2.5f), 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 9.1f)); - Dust dust = Dust.NewDustPerfect(target.Center + offset, Main.rand.NextBool() ? 288 : 121, new Vector2(velOffset.X, velOffset.Y)); + Dust dust = Dust.NewDustPerfect(target.Center + offset, Main.rand.NextBool() ? 288 : 207, new Vector2(velOffset.X, velOffset.Y)); dust.noGravity = false; dust.velocity = velOffset; dust.scale = Main.rand.NextFloat(1.5f, 1.2f); diff --git a/Projectiles/Melee/Shortswords/SaharaSlicersBladeAlt.cs b/Projectiles/Melee/Shortswords/SaharaSlicersBladeAlt.cs index eef61408fd..d24515e39e 100644 --- a/Projectiles/Melee/Shortswords/SaharaSlicersBladeAlt.cs +++ b/Projectiles/Melee/Shortswords/SaharaSlicersBladeAlt.cs @@ -34,8 +34,8 @@ namespace CalamityMod.Projectiles.Melee.Shortswords public override void SetVisualOffsets() { - const int HalfSpriteWidth = 40 / 2; - const int HalfSpriteHeight = 40 / 2; + const int HalfSpriteWidth = 32 / 2; + const int HalfSpriteHeight = 32 / 2; int HalfProjWidth = Projectile.width / 2; int HalfProjHeight = Projectile.height / 2; @@ -83,7 +83,7 @@ namespace CalamityMod.Projectiles.Melee.Shortswords float rot = MathHelper.ToRadians(i * rotFactor); Vector2 offset = new Vector2(Main.rand.NextFloat(0.5f, 2.5f), 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 9.1f)); Vector2 velOffset = new Vector2(Main.rand.NextFloat(0.5f, 2.5f), 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 9.1f)); - Dust dust = Dust.NewDustPerfect(target.Center + offset, Main.rand.NextBool() ? 288 : 121, new Vector2(velOffset.X, velOffset.Y)); + Dust dust = Dust.NewDustPerfect(target.Center + offset, Main.rand.NextBool() ? 288 : 207, new Vector2(velOffset.X, velOffset.Y)); dust.noGravity = false; dust.velocity = velOffset; dust.scale = Main.rand.NextFloat(1.5f, 1.2f); diff --git a/Projectiles/Ranged/BarinadeArrow.cs b/Projectiles/Ranged/BarinadeArrow.cs index 7cecd75002..36075d3f3d 100644 --- a/Projectiles/Ranged/BarinadeArrow.cs +++ b/Projectiles/Ranged/BarinadeArrow.cs @@ -40,7 +40,7 @@ namespace CalamityMod.Projectiles.Ranged { for (int i = 0; i <= 5; i++) { - Dust dust = Dust.NewDustPerfect(Projectile.Center, Main.rand.NextBool(3) ? 216 : 121, Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(15f)) * Main.rand.NextFloat(0.1f, 0.6f), 0, default, Main.rand.NextFloat(1.2f, 1.6f)); + Dust dust = Dust.NewDustPerfect(Projectile.Center, Main.rand.NextBool(3) ? 216 : 207, Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(15f)) * Main.rand.NextFloat(0.1f, 0.6f), 0, default, Main.rand.NextFloat(1.2f, 1.6f)); dust.noGravity = true; } } diff --git a/Projectiles/Ranged/BarinadeArrow.png b/Projectiles/Ranged/BarinadeArrow.png index 6e8c0c4a87..d4720a0d0e 100644 Binary files a/Projectiles/Ranged/BarinadeArrow.png and b/Projectiles/Ranged/BarinadeArrow.png differ diff --git a/Projectiles/Ranged/OntologicalDespoilerHoldout.cs b/Projectiles/Ranged/OntologicalDespoilerHoldout.cs index 438610e813..ca3726c40e 100644 --- a/Projectiles/Ranged/OntologicalDespoilerHoldout.cs +++ b/Projectiles/Ranged/OntologicalDespoilerHoldout.cs @@ -155,7 +155,17 @@ namespace CalamityMod.Projectiles.Ranged inverseTimer--; // Changing Mode - if (Projectile.ai[2] >= 10) + if (Projectile.ai[2] == 20) + { + Projectile.frame = 6; + ShotsLoaded = 0; + if (Time == 0) + { + Projectile.timeLeft = (int)(AftershotCooldownFrames * 1.5f); + OffsetLengthFromArm = 45f; + } + } + else if (Projectile.ai[2] >= 10) { ShotsLoaded = 0; if (Time == 0) @@ -272,14 +282,14 @@ namespace CalamityMod.Projectiles.Ranged for (int i = 0; i < 3; i++) { float angle = i == 0 ? -0.25f : i == 2 ? 0.25f : 0; - Projectile.NewProjectile(Projectile.GetSource_FromThis(), GunTipPosition, fireVec.RotatedBy(angle) * (1 - Math.Abs(angle * 0.25f)), ModContent.ProjectileType(), (int)(Projectile.damage / 1.2f), Projectile.knockBack, Projectile.owner, 0, 0, i); + Projectile.NewProjectile(Projectile.GetSource_FromThis(), GunTipPosition, fireVec.RotatedBy(angle) * (1 - Math.Abs(angle * 0.25f)), ModContent.ProjectileType(), (int)(Projectile.damage), Projectile.knockBack, Projectile.owner, 0, 0, i); } } else { for (int i = 0; i < 2; i++) { - Projectile.NewProjectile(Projectile.GetSource_FromThis(), GunTipPosition, fireVec.RotatedByRandom(0.45f) * Main.rand.NextFloat(0.8f, 1f), ModContent.ProjectileType(), (int)(Projectile.damage / 2.5f), Projectile.knockBack, Projectile.owner, 0, 0, 5); + Projectile.NewProjectile(Projectile.GetSource_FromThis(), GunTipPosition, fireVec.RotatedByRandom(0.45f) * Main.rand.NextFloat(0.8f, 1f), ModContent.ProjectileType(), (int)(Projectile.damage / 4f), Projectile.knockBack, Projectile.owner, 0, 0, 5); } } } @@ -453,7 +463,7 @@ namespace CalamityMod.Projectiles.Ranged SpriteEffects flipSprite = (Projectile.spriteDirection * Owner.gravDir == -1) ? SpriteEffects.FlipHorizontally : SpriteEffects.None; if (!Owner.CantUseHoldout()) { - float rumble = MathHelper.Clamp(CurrentChargingFrames, 0f, Charge2Frames); + float rumble = (Projectile.ai[2] == 20 ? 200 : MathHelper.Clamp(CurrentChargingFrames, 0f, Charge2Frames)); drawPosition += Main.rand.NextVector2Circular(rumble / 120f, rumble / 120f); } diff --git a/Projectiles/Rogue/ScourgeoftheDesertProj.cs b/Projectiles/Rogue/ScourgeoftheDesertProj.cs index 3b9e665621..0cffabe8d1 100644 --- a/Projectiles/Rogue/ScourgeoftheDesertProj.cs +++ b/Projectiles/Rogue/ScourgeoftheDesertProj.cs @@ -59,7 +59,7 @@ namespace CalamityMod.Projectiles.Rogue if (Main.rand.NextBool(2)) { - Dust dust = Dust.NewDustPerfect(Projectile.Center + Main.rand.NextVector2Circular(20, 20), Main.rand.NextBool() ? 288 : 121); + Dust dust = Dust.NewDustPerfect(Projectile.Center + Main.rand.NextVector2Circular(20, 20), Main.rand.NextBool() ? 288 : 207); dust.scale = Main.rand.NextFloat(0.3f, 0.55f); dust.noGravity = true; dust.velocity = -Projectile.velocity * 0.5f; @@ -86,7 +86,7 @@ namespace CalamityMod.Projectiles.Rogue SoundEngine.PlaySound(SoundID.NPCHit11 with { Volume = 1.3f, Pitch = 1.1f }, Projectile.Center); for (int i = 0; i <= 25; i++) { - Dust dust = Dust.NewDustPerfect(Projectile.Center - Projectile.velocity * 6.5f, Main.rand.NextBool() ? 121 : 216, Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(30f)) * Main.rand.NextFloat(0.3f, 0.9f), 0, default, Main.rand.NextFloat(1.3f, 1.8f)); + Dust dust = Dust.NewDustPerfect(Projectile.Center - Projectile.velocity * 6.5f, Main.rand.NextBool() ? 207 : 216, Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(30f)) * Main.rand.NextFloat(0.3f, 0.9f), 0, default, Main.rand.NextFloat(1.3f, 1.8f)); dust.noGravity = true; } PostExitTiles = true; @@ -176,7 +176,7 @@ namespace CalamityMod.Projectiles.Rogue { for (int i = 0; i <= 25; i++) { - Dust dust = Dust.NewDustPerfect(Projectile.Center + Projectile.velocity * 3, Main.rand.NextBool() ? 121 : 216, -Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(30f)) * Main.rand.NextFloat(0.3f, 0.9f), 0, default, Main.rand.NextFloat(1.3f, 1.8f)); + Dust dust = Dust.NewDustPerfect(Projectile.Center + Projectile.velocity * 3, Main.rand.NextBool() ? 207 : 216, -Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(30f)) * Main.rand.NextFloat(0.3f, 0.9f), 0, default, Main.rand.NextFloat(1.3f, 1.8f)); dust.noGravity = true; } Projectile.velocity = SavedOldVelocity * 0.7f; @@ -209,7 +209,7 @@ namespace CalamityMod.Projectiles.Rogue { for (int i = 0; i <= 25; i++) { - Dust dust = Dust.NewDustPerfect(Projectile.Center - Projectile.velocity, Main.rand.NextBool(3) ? 216 : 121, Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(15f)) * Main.rand.NextFloat(0.05f, 2.2f), 0, default, Main.rand.NextFloat(1.5f, 2.8f)); + Dust dust = Dust.NewDustPerfect(Projectile.Center - Projectile.velocity, Main.rand.NextBool(3) ? 216 : 207, Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(15f)) * Main.rand.NextFloat(0.05f, 2.2f), 0, default, Main.rand.NextFloat(1.5f, 2.8f)); dust.noGravity = true; } } diff --git a/Projectiles/Summon/BrittleStarMinion.cs b/Projectiles/Summon/BrittleStarMinion.cs index f5b59b8758..5f5d145125 100644 --- a/Projectiles/Summon/BrittleStarMinion.cs +++ b/Projectiles/Summon/BrittleStarMinion.cs @@ -29,8 +29,8 @@ namespace CalamityMod.Projectiles.Summon public int Time = 0; public override void SetDefaults() { - Projectile.width = 42; - Projectile.height = 42; + Projectile.width = 30; + Projectile.height = 28; Projectile.localNPCHitCooldown = 15; base.SetDefaults(); } @@ -70,7 +70,7 @@ namespace CalamityMod.Projectiles.Summon float rot = MathHelper.ToRadians(i * rotFactor); Vector2 offset = new Vector2(Main.rand.NextFloat(1.5f, 4f), 0).RotatedBy(rot * Main.rand.NextFloat(3.1f, 9.1f)); Vector2 velOffset = new Vector2(Main.rand.NextFloat(1.5f, 4f), 0).RotatedBy(rot * Main.rand.NextFloat(3.1f, 9.1f)); - Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, Main.rand.NextBool(3) ? 216 : 121, new Vector2(velOffset.X, velOffset.Y)); + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, Main.rand.NextBool(3) ? 216 : 207, new Vector2(velOffset.X, velOffset.Y)); dust.noGravity = true; dust.velocity = velOffset; dust.scale = Main.rand.NextFloat(1.3f, 1.9f); @@ -176,7 +176,7 @@ namespace CalamityMod.Projectiles.Summon { for (int i = 0; i <= 5; i++) { - Dust dust = Dust.NewDustPerfect(Projectile.Center - Projectile.velocity, Main.rand.NextBool(3) ? 216 : 121, Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(15f)) * Main.rand.NextFloat(0.05f, 0.4f), 0, default, Main.rand.NextFloat(1.3f, 1.8f)); + Dust dust = Dust.NewDustPerfect(Projectile.Center - Projectile.velocity, Main.rand.NextBool(3) ? 216 : 207, Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(15f)) * Main.rand.NextFloat(0.05f, 0.4f), 0, default, Main.rand.NextFloat(1.3f, 1.8f)); dust.noGravity = true; } SoundEngine.PlaySound(SoundID.DD2_SkeletonHurt with { Pitch = 0.5f }, Projectile.Center); @@ -194,7 +194,7 @@ namespace CalamityMod.Projectiles.Summon float rot = MathHelper.ToRadians(i * rotFactor); Vector2 offset = new Vector2(Main.rand.NextFloat(0.5f, 2.5f), 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 9.1f)); Vector2 velOffset = new Vector2(Main.rand.NextFloat(0.5f, 2.5f), 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 9.1f)); - Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, Main.rand.NextBool(3) ? 216 : 121, new Vector2(velOffset.X, velOffset.Y)); + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, Main.rand.NextBool(3) ? 216 : 207, new Vector2(velOffset.X, velOffset.Y)); dust.noGravity = true; dust.velocity = velOffset; dust.scale = Main.rand.NextFloat(1.3f, 1.8f); diff --git a/Projectiles/Summon/BrittleStarMinion.png b/Projectiles/Summon/BrittleStarMinion.png index 4497bd57e6..739f28d509 100644 Binary files a/Projectiles/Summon/BrittleStarMinion.png and b/Projectiles/Summon/BrittleStarMinion.png differ 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 { diff --git a/Scenes/MusicScenes/RevBoCIntroMusicScene.cs b/Scenes/MusicScenes/RevBoCIntroMusicScene.cs index 1a0a9caecc..4d983efd0b 100644 --- a/Scenes/MusicScenes/RevBoCIntroMusicScene.cs +++ b/Scenes/MusicScenes/RevBoCIntroMusicScene.cs @@ -1,5 +1,5 @@ using System; -using CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses; +using CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses.BrainOfCthulhu; using CalamityMod.World; using Terraria; using Terraria.ID; @@ -56,7 +56,7 @@ namespace CalamityMod.Scenes.MusicScenes return revBrain.SpawnTime != 0 && (revBrain.Time - Math.Abs(revBrain.SpawnTime) < 420); } - public override int Music => RevBoCSystem.PreviousMusic >= 0 ? RevBoCSystem.PreviousMusic : MusicID.Crimson; //Keeps the music that was playing prior to BoC being spawned + public override int Music => BrainOfCthulhuSystem.PreviousMusic >= 0 ? BrainOfCthulhuSystem.PreviousMusic : MusicID.Crimson; //Keeps the music that was playing prior to BoC being spawned public override SceneEffectPriority Priority => SceneEffectPriority.BossMedium; } 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/NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Roar.ogg b/Sounds/Custom/BrainOfCthulhu/BoC_Rev_Roar.ogg similarity index 100% rename from NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Roar.ogg rename to Sounds/Custom/BrainOfCthulhu/BoC_Rev_Roar.ogg diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Shield_Down.ogg b/Sounds/Custom/BrainOfCthulhu/BoC_Rev_Shield_Down.ogg similarity index 100% rename from NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Shield_Down.ogg rename to Sounds/Custom/BrainOfCthulhu/BoC_Rev_Shield_Down.ogg diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Shield_Up.ogg b/Sounds/Custom/BrainOfCthulhu/BoC_Rev_Shield_Up.ogg similarity index 100% rename from NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Shield_Up.ogg rename to Sounds/Custom/BrainOfCthulhu/BoC_Rev_Shield_Up.ogg diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Short_Roar.ogg b/Sounds/Custom/BrainOfCthulhu/BoC_Rev_Short_Roar.ogg similarity index 100% rename from NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Short_Roar.ogg rename to Sounds/Custom/BrainOfCthulhu/BoC_Rev_Short_Roar.ogg diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Stun_Hit1.ogg b/Sounds/Custom/BrainOfCthulhu/BoC_Rev_Stun_Hit1.ogg similarity index 100% rename from NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Stun_Hit1.ogg rename to Sounds/Custom/BrainOfCthulhu/BoC_Rev_Stun_Hit1.ogg diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Stun_Hit2.ogg b/Sounds/Custom/BrainOfCthulhu/BoC_Rev_Stun_Hit2.ogg similarity index 100% rename from NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Stun_Hit2.ogg rename to Sounds/Custom/BrainOfCthulhu/BoC_Rev_Stun_Hit2.ogg diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Stun_Hit3.ogg b/Sounds/Custom/BrainOfCthulhu/BoC_Rev_Stun_Hit3.ogg similarity index 100% rename from NPCs/VanillaNPCAIOverrides/Bosses/BoC_Rev_Stun_Hit3.ogg rename to Sounds/Custom/BrainOfCthulhu/BoC_Rev_Stun_Hit3.ogg diff --git a/Systems/Collections/CalamityNPCSets.cs b/Systems/Collections/CalamityNPCSets.cs index 10209c6308..e16ef7e0aa 100644 --- a/Systems/Collections/CalamityNPCSets.cs +++ b/Systems/Collections/CalamityNPCSets.cs @@ -235,9 +235,9 @@ namespace CalamityMod.Systems.Collections { NPCType(), 21000 }, { NPCID.EyeofCthulhu, 450000 }, // 30 seconds { NPCID.ServantofCthulhu, 6000 }, - { NPCID.EaterofWorldsHead, 10000 }, // 30 seconds + immunity timer at start - { NPCID.EaterofWorldsBody, 10000 }, - { NPCID.EaterofWorldsTail, 10000 }, + { NPCID.EaterofWorldsHead, 15000 }, // 30 seconds + immunity timer at start + { NPCID.EaterofWorldsBody, 15000 }, + { NPCID.EaterofWorldsTail, 15000 }, { NPCID.BrainofCthulhu, 100000 }, // 30 seconds with creepers { NPCID.Creeper, 10000 }, { NPCID.QueenBee, 315000 }, // 30 seconds diff --git a/Systems/Graphic/DoGVisualsManager.cs b/Systems/Graphic/DoGVisualsManager.cs index 2dde39a0fe..fc913ca06a 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; } @@ -158,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(clearColor: Color.Transparent)) + { + DrawDistortionRiftBackground(); + } - Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearWrap, DepthStencilState.None, Main.Rasterizer, null, CalamityUtils.BackgroundMatrix); + using (DistortionRiftPrimitivesTarget.Scope(clearColor: Color.Transparent)) + { + 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(clearColor: Color.Transparent)) + { + 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/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/Graphic/PixelationSystem/PixelationManager.cs b/Systems/Graphic/PixelationSystem/PixelationManager.cs index 151add53f1..a1f47dea93 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) @@ -163,28 +159,27 @@ 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); } } - 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) { - 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(clearColor: Color.Transparent)) { - 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(); @@ -198,7 +193,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(); } } @@ -221,9 +216,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 +240,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; } } 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 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/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 0000000000..b4bee1eaa7 Binary files /dev/null and b/Tiles/Furniture/Paintings/ForgivenessPaintingTile.png differ diff --git a/UI/DialogueDisplay/DialogueDisplayUI.cs b/UI/DialogueDisplay/DialogueDisplayUI.cs index 4bf1265e07..153eac8d15 100644 --- a/UI/DialogueDisplay/DialogueDisplayUI.cs +++ b/UI/DialogueDisplay/DialogueDisplayUI.cs @@ -1,27 +1,25 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.IO; using System.Linq; -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; -using static System.Runtime.InteropServices.JavaScript.JSType; +using static CalamityMod.Packets.StartDialogueDisplayPacket; using static ReLogic.Graphics.DynamicSpriteFont; namespace CalamityMod.UI.DialogueDisplay @@ -63,8 +61,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) @@ -528,7 +531,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 { @@ -911,6 +914,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) @@ -940,15 +980,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); @@ -963,8 +994,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; } @@ -1009,13 +1040,35 @@ 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(); - 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; @@ -1048,13 +1101,35 @@ 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) { + 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); + 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; @@ -1120,6 +1195,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) { 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; diff --git a/UI/VanillaBossBars/RevBrainOfCthulhuBossBar.cs b/UI/VanillaBossBars/RevBrainOfCthulhuBossBar.cs index dc5261450e..70a5c32f90 100644 --- a/UI/VanillaBossBars/RevBrainOfCthulhuBossBar.cs +++ b/UI/VanillaBossBars/RevBrainOfCthulhuBossBar.cs @@ -1,4 +1,4 @@ -using CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses; +using CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses.BrainOfCthulhu; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; diff --git a/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs b/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs index 4d4abc310e..5639dba82e 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); + ManagedRenderTargetPool.Shared.ResizeTargets(); } } diff --git a/Utilities/DrawingUtils.cs b/Utilities/DrawingUtils.cs index 362d3fc71e..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)) { } } /// @@ -818,6 +817,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. diff --git a/Utilities/MainThreadedFileSystemWatcher.cs b/Utilities/MainThreadedFileSystemWatcher.cs new file mode 100644 index 0000000000..a605e9e674 --- /dev/null +++ b/Utilities/MainThreadedFileSystemWatcher.cs @@ -0,0 +1,179 @@ +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; + +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 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) => + { + if (FileNameFilter != null && !FileNameFilter.IsMatch(System.IO.Path.GetFileName(arg.Name))) + return; + + lock (_ChangedQueue) + { + _ChangedQueue[arg.FullPath] = arg; + _HasQueueInFrame = true; + } + }; + + _FSW.Renamed += (o, arg) => + { + if (FileNameFilter != null && !FileNameFilter.IsMatch(System.IO.Path.GetFileName(arg.Name))) + return; + + lock (_RenamedQueue) + { + _RenamedQueue[arg.FullPath] = arg; + _HasQueueInFrame = true; + } + }; + + MainThreadedFileSystemWatcherSystem.Register(this); + } + + 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]; + } + + public static void Unregister(MainThreadedFileSystemWatcher watcher) + { + _WatchersList.Remove(watcher); + _Watchers = [.. _WatchersList]; + } + + void ILoadable.Load(Mod mod) + { + Main.OnTickForThirdPartySoftwareOnly += Tick; + } + + void ILoadable.Unload() + { + Main.OnTickForThirdPartySoftwareOnly -= Tick; + _WatchersList?.Clear(); + _Watchers = []; + } + + private void Tick() + { + foreach (var watcher in _Watchers) + { + if (!watcher._HasQueueInFrame) + continue; + + HandleQueuedEvents(watcher); + } + } + + private static void HandleQueuedEvents(MainThreadedFileSystemWatcher watcher) + { + 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; + } + } +}