diff --git a/CalPlayer/CalamityPlayer.cs b/CalPlayer/CalamityPlayer.cs index 21b4dcfa9e..7083ca2e61 100644 --- a/CalPlayer/CalamityPlayer.cs +++ b/CalPlayer/CalamityPlayer.cs @@ -1610,7 +1610,6 @@ namespace CalamityMod.CalPlayer noLifeRegen = false; // Shields. Has to intentionally be above resetting accessories and armor or the shields would clear instantly - drawnAnyShieldThisFrame = false; if (!roverDrive) RoverDriveShieldDurability = 0; if (!lunicCorpsSet) diff --git a/CalPlayer/CalamityPlayerDrawParameters.cs b/CalPlayer/CalamityPlayerDrawParameters.cs new file mode 100644 index 0000000000..dd4577c6cc --- /dev/null +++ b/CalPlayer/CalamityPlayerDrawParameters.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Items.Accessories; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.ModLoader; + +namespace CalamityMod.CalPlayer +{ + public struct CalamityPlayerDrawingParameters + { + public float ProfanedShieldStrength; + public Color ProfanedShieldColor; + + public float RoverShieldCharge; + public float SpongeShieldCharge; + public float LunicShieldCharge; + } + + public partial class CalamityPlayer : ModPlayer + { + public CalamityPlayerDrawingParameters drawingParameters; + + private void UpdateDrawingParameters() + { + bool isVanityOnly = pSoulShieldVisible && !pSoulArtifact; + bool shouldNotDraw = andromedaState >= AndromedaPlayerState.LargeRobot; //I am not dealing with drawing that :taxevasion: + bool shieldExists = isVanityOnly || pSoulShieldDurability > 0; + if (pSoulShieldVisible && !shouldNotDraw && shieldExists) + { + ProfanedSoulCrystal.DetermineTransformationEligibility(Player); + var psState = (int)ProfanedSoulCrystal.GetPscStateFor(Player, profanedCrystalAnim >= 0); + var psc = profanedCrystalBuffs || (profanedCrystalAnim >= 0 && psState >= (int)ProfanedSoulCrystal.ProfanedSoulCrystalState.Buffs); + + float visualShieldStrength = 1f; + if (!isVanityOnly) + { + float max = psc ? ProfanedSoulCrystal.ShieldDurabilityMax : ProfanedSoulArtifact.ShieldDurabilityMax; + float shieldDurabilityRatio = pSoulShieldDurability / max; + visualShieldStrength = MathF.Pow(shieldDurabilityRatio, 0.5f); + } + + Color shieldColor = ProfanedSoulCrystal.GetColorForPsc(psState, Main.dayTime); + if (psState >= (int)(ProfanedSoulCrystal.ProfanedSoulCrystalState.Buffs)) + { + bool tester = ProfanedSoulCrystal.contributorNames.Any(name => name.Equals(Player.name)); + shieldColor = tester ? CalamityUtils.ColorSwap(new Color(255, 166, 0), new Color(25, 250, 25) * 0.8f, 6f) : + ProfanedSoulCrystal.GetLerpedColorForPsc(this); + } + + drawingParameters.ProfanedShieldColor = shieldColor; + drawingParameters.ProfanedShieldStrength = visualShieldStrength; + } + else + { + drawingParameters.ProfanedShieldStrength = -1.0f; + drawingParameters.ProfanedShieldColor = Color.White; + } + } + } +} diff --git a/CalPlayer/CalamityPlayerMiscEffects.cs b/CalPlayer/CalamityPlayerMiscEffects.cs index c4e0b1c6da..2726566104 100644 --- a/CalPlayer/CalamityPlayerMiscEffects.cs +++ b/CalPlayer/CalamityPlayerMiscEffects.cs @@ -155,6 +155,9 @@ namespace CalamityMod.CalPlayer // Handle Androomba's Right Click function AndroombaRightClick(); + // Drawing parameters + UpdateDrawingParameters(); + // Update all particle sets for items. // This must be done here instead of in the item logic because these sets are not properly instanced // in the global classes. Attempting to update them there will cause multiple updates to one set for multiple items. diff --git a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs index d0570d372e..70bc38faba 100644 --- a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs +++ b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs @@ -157,7 +157,7 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers return; // Leave if nothing to draw. - if (!RenderersToDrawThisFrame.Any()) + if (RenderersToDrawThisFrame.Count <= 0) return; // Sort the list by draw order. diff --git a/Graphics/Renderers/RendererManager.cs b/Graphics/Renderers/RendererManager.cs index e7e5967a5f..64289533ea 100644 --- a/Graphics/Renderers/RendererManager.cs +++ b/Graphics/Renderers/RendererManager.cs @@ -86,29 +86,22 @@ namespace CalamityMod.Graphics.Renderers if (Main.gameMenu || Main.dedServ) return; + // Reset drawn frame check + foreach (var player in Main.ActivePlayers) + { + player.Calamity().drawnAnyShieldThisFrame = false; + } + foreach (var renderer in Renderers) { if (!renderer.ShouldDraw) continue; - try + Main.spriteBatch.SafeAction(() => { renderer.MainTarget.SwapTo(Color.Transparent); - Main.spriteBatch.TryBegin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Main.GameViewMatrix.TransformationMatrix); renderer.DrawToTarget(Main.spriteBatch); - } - catch (Exception e) - { - Main.QueueMainThreadAction(() => - { - CalamityMod.Instance.Logger.Error($"Exception Found on RenderDetour: {e}"); - }); - } - finally - { - // Always end the Batch! - Main.spriteBatch.TryEnd(); - } + }); } Main.instance.GraphicsDevice.SetRenderTarget(null); diff --git a/Items/Accessories/ProfanedSoulArtifact.cs b/Items/Accessories/ProfanedSoulArtifact.cs index 1d866fbb10..cb561fd4ff 100644 --- a/Items/Accessories/ProfanedSoulArtifact.cs +++ b/Items/Accessories/ProfanedSoulArtifact.cs @@ -37,22 +37,16 @@ namespace CalamityMod.Items.Accessories { get { - bool result = false; foreach (Player player in Main.ActivePlayers) { if (player.outOfRange || player.dead) continue; CalamityPlayer modPlayer = player.Calamity(); - - // Do not render the shield if its visibility is off (or it does not exist) - bool isVanityOnly = modPlayer.pSoulShieldVisible && !modPlayer.pSoulArtifact; - bool shouldNotDraw = modPlayer.andromedaState >= AndromedaPlayerState.LargeRobot; //I am not dealing with drawing that :taxevasion: - bool shieldExists = isVanityOnly || modPlayer.pSoulShieldDurability > 0; - bool shouldntDraw = !modPlayer.pSoulShieldVisible || modPlayer.drawnAnyShieldThisFrame || shouldNotDraw || !shieldExists; - result |= !shouldntDraw; + if (modPlayer.drawingParameters.ProfanedShieldStrength > 0.0f) + return true; } - return result; + return false; } } @@ -115,8 +109,6 @@ namespace CalamityMod.Items.Accessories // Profaned Soul shields will be drawn for each player with the Profaned Soul artifact/crystal, yes. // But there is no guarantee that the shields will be in the right condition for each player. // Visibility is not net synced, for example. - bool alreadyDrawnShieldForPlayer = false; - foreach (Player player in Main.ActivePlayers) { if (player.outOfRange || player.dead) @@ -124,78 +116,53 @@ namespace CalamityMod.Items.Accessories CalamityPlayer modPlayer = player.Calamity(); - // Do not render the shield if its visibility is off (or it does not exist) - bool isVanityOnly = modPlayer.pSoulShieldVisible && !modPlayer.pSoulArtifact; - bool shouldNotDraw = modPlayer.andromedaState >= AndromedaPlayerState.LargeRobot; //I am not dealing with drawing that :taxevasion: - bool shieldExists = isVanityOnly || modPlayer.pSoulShieldDurability > 0; - if (!modPlayer.pSoulShieldVisible || modPlayer.drawnAnyShieldThisFrame || shouldNotDraw || !shieldExists) + if (modPlayer.drawnAnyShieldThisFrame) + continue; + + if (modPlayer.drawingParameters.ProfanedShieldStrength <= 0.0f) continue; // Scale the shield is drawn at. // The "i" parameter is to make different player's shields not be perfectly synced. int i = player.whoAmI; - float scale = 0.15f + 0.03f * (0.5f + 0.5f * (float)Math.Sin(Main.GlobalTimeWrappedHourly * 0.5f + i * 0.2f)); + float scale = 0.15f + 0.03f * (0.5f + 0.5f * MathF.Sin(Main.GlobalTimeWrappedHourly * 0.5f + i * 0.2f)); + float visualShieldStrength = modPlayer.drawingParameters.ProfanedShieldStrength; + Color shieldColor = modPlayer.drawingParameters.ProfanedShieldColor; - if (!alreadyDrawnShieldForPlayer) + // The scale used for the noise overlay polygons also grows and shrinks + // This is intentionally out of sync with the shield, and intentionally desynced per player + // Don't put this anywhere less than 0.25f or higher than 1f. The higher it is, the denser / more zoomed out the noise overlay is. + float noiseScale = MathHelper.Lerp(0.4f, 0.8f, MathF.Sin(Main.GlobalTimeWrappedHourly * 0.3f) * 0.5f + 0.5f); + + // Define shader parameters + Effect shieldEffect = Filters.Scene["CalamityMod:RoverDriveShield"].GetShader().Shader; + shieldEffect.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly * 0.058f); // Scrolling speed of polygonal overlay + shieldEffect.Parameters["blowUpPower"].SetValue(2.8f); + shieldEffect.Parameters["blowUpSize"].SetValue(0.4f); + shieldEffect.Parameters["noiseScale"].SetValue(noiseScale); + + // Shield opacity multiplier slightly changes, this is independent of current shield strength + float baseShieldOpacity = 0.9f + 0.1f * MathF.Sin(Main.GlobalTimeWrappedHourly * 1.95f); + float minShieldStrengthOpacityMultiplier = 0.5f; + float finalShieldOpacity = baseShieldOpacity * MathHelper.Lerp(minShieldStrengthOpacityMultiplier, 1f, visualShieldStrength); + shieldEffect.Parameters["shieldOpacity"].SetValue(finalShieldOpacity); + shieldEffect.Parameters["shieldEdgeBlendStrenght"].SetValue(4f); + + Color primaryEdgeColor = new Color(230, 199, 102) * 0.8f; + Color secondaryEdgeColor = new Color(249, 231, 217) * 0.8f; + Color edgeColor = CalamityUtils.MulticolorLerp(Main.GlobalTimeWrappedHourly * 0.2f, primaryEdgeColor, secondaryEdgeColor); + + // Define shader parameters for shield color + shieldEffect.Parameters["shieldColor"].SetValue(shieldColor.ToVector3()); + shieldEffect.Parameters["shieldEdgeColor"].SetValue(edgeColor.ToVector3()); + + // GOD I LOVE END BEGIN CAN THIS GAME PLEASE BE SWALLOWED BY THE FIRES OF HELL THANKS + // yes I copy pasted that comment, I hate end begin that much + // I also copy pasted that comment, this time for consistency :hdfailure: + + var matrix = Main.GameViewMatrix.TransformationMatrix; + Main.spriteBatch.SafeBegin(SpriteSortMode.Immediate, BatchSetting.Additive, shieldEffect, matrix, () => { - CalamityPlayer localModPlayer = Main.LocalPlayer.Calamity(); - DetermineTransformationEligibility(localModPlayer.Player); - var psState = (int)GetPscStateFor(localModPlayer.Player, localModPlayer.profanedCrystalAnim >= 0); - var psc = localModPlayer.profanedCrystalBuffs || (localModPlayer.profanedCrystalAnim >= 0 && psState >= (int)ProfanedSoulCrystalState.Buffs); - - scale += ((ProfanedSoulCrystalState)psState) == ProfanedSoulCrystalState.Empowered ? 0.05f : psc ? 0.025f : 0f; - if (localModPlayer.profanedCrystalAnim >= 0) - scale = MathHelper.Lerp(0f, scale, ((float)maxPscAnimTime - (float)localModPlayer.profanedCrystalAnim) / (float)maxPscAnimTime); //i don't like casting this many times, i'm not a fucking wizard - - float visualShieldStrength = 1f; - if (!isVanityOnly) - { - float max = psc ? ProfanedSoulCrystal.ShieldDurabilityMax : ShieldDurabilityMax; - float shieldDurabilityRatio = localModPlayer.pSoulShieldDurability / max; - visualShieldStrength = MathF.Pow(shieldDurabilityRatio, 0.5f); - } - - // The scale used for the noise overlay polygons also grows and shrinks - // This is intentionally out of sync with the shield, and intentionally desynced per player - // Don't put this anywhere less than 0.25f or higher than 1f. The higher it is, the denser / more zoomed out the noise overlay is. - float noiseScale = MathHelper.Lerp(0.4f, 0.8f, (float)Math.Sin(Main.GlobalTimeWrappedHourly * 0.3f) * 0.5f + 0.5f); - - // Define shader parameters - Effect shieldEffect = Filters.Scene["CalamityMod:RoverDriveShield"].GetShader().Shader; - shieldEffect.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly * 0.058f); // Scrolling speed of polygonal overlay - shieldEffect.Parameters["blowUpPower"].SetValue(2.8f); - shieldEffect.Parameters["blowUpSize"].SetValue(0.4f); - shieldEffect.Parameters["noiseScale"].SetValue(noiseScale); - - // Shield opacity multiplier slightly changes, this is independent of current shield strength - float baseShieldOpacity = 0.9f + 0.1f * MathF.Sin(Main.GlobalTimeWrappedHourly * 1.95f); - float minShieldStrengthOpacityMultiplier = 0.5f; - float finalShieldOpacity = baseShieldOpacity * MathHelper.Lerp(minShieldStrengthOpacityMultiplier, 1f, visualShieldStrength); - shieldEffect.Parameters["shieldOpacity"].SetValue(finalShieldOpacity); - shieldEffect.Parameters["shieldEdgeBlendStrenght"].SetValue(4f); - - // Profaned Soul shields are not team specific - Color shieldColor = GetColorForPsc(psState, Main.dayTime); - if (psState >= (int)(ProfanedSoulCrystalState.Buffs)) - { - bool tester = contributorNames.Any(name => name.Equals(localModPlayer.Player.name)); - shieldColor = tester ? CalamityUtils.ColorSwap(new Color(255, 166, 0), new Color(25, 250, 25) * 0.8f, 6f) : - GetLerpedColorForPsc(modPlayer); - } - - Color primaryEdgeColor = new Color(230, 199, 102) * 0.8f; - Color secondaryEdgeColor = new Color(249, 231, 217) * 0.8f; - Color edgeColor = CalamityUtils.MulticolorLerp(Main.GlobalTimeWrappedHourly * 0.2f, primaryEdgeColor, secondaryEdgeColor); - - // Define shader parameters for shield color - shieldEffect.Parameters["shieldColor"].SetValue(shieldColor.ToVector3()); - shieldEffect.Parameters["shieldEdgeColor"].SetValue(edgeColor.ToVector3()); - - // GOD I LOVE END BEGIN CAN THIS GAME PLEASE BE SWALLOWED BY THE FIRES OF HELL THANKS - // yes I copy pasted that comment, I hate end begin that much - // I also copy pasted that comment, this time for consistency :hdfailure: - Main.spriteBatch.End(); - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, shieldEffect, Main.GameViewMatrix.TransformationMatrix); // Fetch shield heat overlay texture (this is the neutrons fed to the shader) HeatTex ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Neurons2"); Vector2 pos = player.MountedCenter + player.gfxOffY * Vector2.UnitY - Main.screenPosition; @@ -208,22 +175,16 @@ namespace CalamityMod.Items.Accessories Rectangle shieldFrame = shieldTexture.Frame(); Vector2 origin = shieldFrame.Size() * 0.5f; Main.spriteBatch.End(); + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Main.GameViewMatrix.TransformationMatrix); Main.spriteBatch.Draw(shieldTexture, pos, shieldFrame, shieldColor * 0.5f, player.fullRotation, origin, shieldScale, SpriteEffects.None, 0f); Main.spriteBatch.Draw(shieldTexture, pos, shieldFrame, secondaryEdgeColor * 0.5f, player.fullRotation, origin, shieldScale * 0.95f, SpriteEffects.None, 0f); Main.spriteBatch.Draw(shieldTexture, pos, shieldFrame, shieldColor * 0.5f, player.fullRotation, origin, shieldScale, SpriteEffects.None, 0f); Main.spriteBatch.Draw(shieldTexture, pos, shieldFrame, secondaryEdgeColor * 0.5f, player.fullRotation, origin, shieldScale * 0.95f, SpriteEffects.None, 0f); - } - - alreadyDrawnShieldForPlayer = true; + Main.spriteBatch.End(); + }); modPlayer.drawnAnyShieldThisFrame = true; } - - if (alreadyDrawnShieldForPlayer) - { - Main.spriteBatch.End(); - Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Main.Transform); - } } } } diff --git a/Items/Accessories/ProfanedSoulCrystal.cs b/Items/Accessories/ProfanedSoulCrystal.cs index 42be000b5f..45fb36ceb9 100644 --- a/Items/Accessories/ProfanedSoulCrystal.cs +++ b/Items/Accessories/ProfanedSoulCrystal.cs @@ -41,22 +41,16 @@ namespace CalamityMod.Items.Accessories { get { - bool result = false; foreach (Player player in Main.ActivePlayers) { if (player.outOfRange || player.dead) continue; CalamityPlayer modPlayer = player.Calamity(); - - // Do not render the shield if its visibility is off (or it does not exist) - bool isVanityOnly = modPlayer.pSoulShieldVisible && !modPlayer.pSoulArtifact; - bool shouldNotDraw = modPlayer.andromedaState >= AndromedaPlayerState.LargeRobot; //I am not dealing with drawing that :taxevasion: - bool shieldExists = isVanityOnly || modPlayer.pSoulShieldDurability > 0; - bool shouldntDraw = !modPlayer.pSoulShieldVisible || modPlayer.drawnAnyShieldThisFrame || shouldNotDraw || !shieldExists; - result |= !shouldntDraw; + if (modPlayer.drawingParameters.ProfanedShieldStrength > 0.0f) + return true; } - return result; + return false; } } diff --git a/Utilities/DrawingUtils.BatchSetting.cs b/Utilities/DrawingUtils.BatchSetting.cs new file mode 100644 index 0000000000..982e3200d9 --- /dev/null +++ b/Utilities/DrawingUtils.BatchSetting.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.Graphics; +using Terraria; + +namespace CalamityMod +{ + public class BatchSetting(BlendState blend, SamplerState sampler, DepthStencilState depthStencil, RasterizerState rasterizer) + { + public readonly BlendState blendState = blend; + public readonly SamplerState samplerState = sampler; + public readonly DepthStencilState depthStencilState = depthStencil; + public readonly RasterizerState rasterizerState = rasterizer; + + public static readonly BatchSetting AlphaBlend = new( + BlendState.AlphaBlend, + SamplerState.PointClamp, + DepthStencilState.None, + RasterizerState.CullCounterClockwise + ); + + public static readonly BatchSetting Additive = new( + BlendState.Additive, + SamplerState.PointClamp, + DepthStencilState.None, + RasterizerState.CullCounterClockwise + ); + + public static readonly BatchSetting NonPremultiplied = new( + BlendState.NonPremultiplied, + SamplerState.PointClamp, + DepthStencilState.None, + RasterizerState.CullCounterClockwise + ); + + public static readonly BatchSetting Opaque = new( + BlendState.Opaque, + SamplerState.PointClamp, + DepthStencilState.None, + RasterizerState.CullCounterClockwise + ); + } +} diff --git a/Utilities/DrawingUtils.SpriteBatch.cs b/Utilities/DrawingUtils.SpriteBatch.cs new file mode 100644 index 0000000000..94168b2a8a --- /dev/null +++ b/Utilities/DrawingUtils.SpriteBatch.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; + +namespace CalamityMod +{ + public static partial class CalamityUtils + { + // Cached for efficiency purposes. + private const BindingFlags Bind_Private_Instance = BindingFlags.NonPublic | BindingFlags.Instance; + private static readonly FastField Fld_BeginCalled = new("beginCalled", Bind_Private_Instance); + private static readonly FastField Fld_SortMode = new("sortMode", Bind_Private_Instance); + private static readonly FastField Fld_BlendState = new("blendState", Bind_Private_Instance); + private static readonly FastField Fld_SamplerState = new("samplerState", Bind_Private_Instance); + private static readonly FastField Fld_DepthStencilState = new("depthStencilState", Bind_Private_Instance); + private static readonly FastField Fld_RasterizerState = new("rasterizerState", Bind_Private_Instance); + private static readonly FastField Fld_TransformMatrix = new("transformMatrix", Bind_Private_Instance); + private static readonly FastField Fld_CustomEffect = new("customEffect", Bind_Private_Instance); + + /// + /// Sets a 's arbitrarily. + /// + /// The sprite batch. + /// The blend state to use. + public static void SetBlendState(this SpriteBatch spriteBatch, BlendState blendState) + { + spriteBatch.End(); + spriteBatch.Begin(SpriteSortMode.Immediate, blendState, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Main.GameViewMatrix.TransformationMatrix); + } + + /// + /// Determines if a is in a lock due to a call. + /// + /// The sprite batch to check. + public static bool HasBeginBeenCalled(this SpriteBatch spriteBatch) + { + return Fld_BeginCalled.Get(spriteBatch); + } + + public static void SafeAction(this SpriteBatch spriteBatch, Action action) + { + if (spriteBatch is null) + return; + + if (spriteBatch.HasBeginBeenCalled()) + { + var oldSort = Fld_SortMode.Get(spriteBatch); + var oldBlend = Fld_BlendState.Get(spriteBatch); + var oldSampler = Fld_SamplerState.Get(spriteBatch); + var oldDepths = Fld_DepthStencilState.Get(spriteBatch); + var oldRaster = Fld_RasterizerState.Get(spriteBatch); + var oldEffect = Fld_CustomEffect.Get(spriteBatch); + var oldMtx = Fld_TransformMatrix.Get(spriteBatch); + try + { + action?.Invoke(); + } + finally + { + // If something has started in this block, restore the state to previous one + spriteBatch.TryEnd(); + spriteBatch.TryBegin(oldSort, oldBlend, oldSampler, oldDepths, oldRaster, oldEffect, oldMtx); + } + } + else + { + try + { + action?.Invoke(); + } + finally + { + // Initial State was off, turn off the batching + spriteBatch.TryEnd(); + } + } + } + + /// + /// Starts SpriteBatch then Re-Begin batch with old settings when it's all done + /// + /// + /// + /// + /// + /// + /// + public static void SafeBegin(this SpriteBatch spriteBatch, SpriteSortMode sortMode, + BatchSetting settings, + Effect effect, + Matrix transformMatrix, + Action batchCallback + ) + { + if (spriteBatch is null) + return; + + spriteBatch.SafeAction(() => + { + spriteBatch.TryEnd(); + spriteBatch.TryBegin(sortMode, settings.blendState, settings.samplerState, settings.depthStencilState, settings.rasterizerState, effect, transformMatrix); + batchCallback?.Invoke(); + }); + } + + public static bool TryBegin(this SpriteBatch spriteBatch, SpriteSortMode sortMode, + BlendState blendState, + SamplerState samplerState, + DepthStencilState depthStencilState, + RasterizerState rasterizerState, + Effect effect, + Matrix transformMatrix) + { + if (spriteBatch.HasBeginBeenCalled()) + { + return false; + } + else + { + spriteBatch.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, transformMatrix); + return true; + } + } + + public static bool TryEnd(this SpriteBatch spriteBatch) + { + if (!spriteBatch.HasBeginBeenCalled()) + { + return false; + } + else + { + spriteBatch.End(); + return true; + } + } + } +} diff --git a/Utilities/DrawingUtils.cs b/Utilities/DrawingUtils.cs index da593e5423..092f151764 100644 --- a/Utilities/DrawingUtils.cs +++ b/Utilities/DrawingUtils.cs @@ -358,61 +358,6 @@ namespace CalamityMod projectionMatrix = Matrix.CreateOrthographicOffCenter(0f, width * zoom.X, 0f, height * zoom.Y, 0f, 1f) * zoomScaleMatrix; } - /// - /// Sets a 's arbitrarily. - /// - /// The sprite batch. - /// The blend state to use. - public static void SetBlendState(this SpriteBatch spriteBatch, BlendState blendState) - { - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, blendState, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Main.GameViewMatrix.TransformationMatrix); - } - - // Cached for efficiency purposes. - internal static readonly FieldInfo BeginCalled = typeof(SpriteBatch).GetField("beginCalled", BindingFlags.NonPublic | BindingFlags.Instance); - - /// - /// Determines if a is in a lock due to a call. - /// - /// The sprite batch to check. - public static bool HasBeginBeenCalled(this SpriteBatch spriteBatch) - { - return (bool)BeginCalled.GetValue(spriteBatch); - } - - public static bool TryBegin(this SpriteBatch spriteBatch, SpriteSortMode sortMode, - BlendState blendState, - SamplerState samplerState, - DepthStencilState depthStencilState, - RasterizerState rasterizerState, - Effect effect, - Matrix transformMatrix) - { - if (spriteBatch.HasBeginBeenCalled()) - { - return false; - } - else - { - spriteBatch.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, transformMatrix); - return true; - } - } - - public static bool TryEnd(this SpriteBatch spriteBatch) - { - if (!spriteBatch.HasBeginBeenCalled()) - { - return false; - } - else - { - spriteBatch.End(); - return true; - } - } - /// /// Draws a line significantly more efficiently than using just one scaled line texture. Positions are automatically converted to screen coordinates. /// diff --git a/Utilities/ReflectionHelper.cs b/Utilities/ReflectionHelper.cs new file mode 100644 index 0000000000..cad3cd63bd --- /dev/null +++ b/Utilities/ReflectionHelper.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using System.Text; +using System.Threading.Tasks; +using Terraria.GameContent; + +namespace CalamityMod +{ + public class FastField(FieldInfo fieldInfo) + { + private Action _Setter = ReflectionHelper.CreateFieldSetter(fieldInfo); + private Func _Getter = ReflectionHelper.CreateFieldGetter(fieldInfo); + + public FastField(string fieldName, BindingFlags flags) : this(typeof(T).GetField(fieldName, flags)) + { + + } + + public ValueType Get(T instance) + { + return _Getter(instance); + } + + public void Set(T instance, ValueType newValue) + { + _Setter(instance, newValue); + } + } + + public static class ReflectionHelper + { + public static Action CreateFieldSetter(FieldInfo fieldInfo) + { + string methodName = fieldInfo.ReflectedType.FullName + ".set_" + fieldInfo.Name; + DynamicMethod setterMethod = new DynamicMethod(methodName, null, [typeof(T), typeof(ValueType)], true); + ILGenerator gen = setterMethod.GetILGenerator(); + + gen.Emit(OpCodes.Ldarg_0); + gen.Emit(OpCodes.Ldarg_1); + gen.Emit(OpCodes.Stfld, fieldInfo); + gen.Emit(OpCodes.Ret); + + return (Action)setterMethod.CreateDelegate(typeof(Action)); + } + + public static Func CreateFieldGetter(FieldInfo fieldInfo) + { + string methodName = fieldInfo.ReflectedType.FullName + ".get_" + fieldInfo.Name; + DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(ValueType), [typeof(T)], true); + ILGenerator gen = getterMethod.GetILGenerator(); + + gen.Emit(OpCodes.Ldarg_0); + gen.Emit(OpCodes.Ldfld, fieldInfo); + gen.Emit(OpCodes.Ret); + + return (Func)getterMethod.CreateDelegate(typeof(Func)); + } + } +}