Rewrite Rendering Code for ProfanedShield

This commit is contained in:
Flowaria authored and Cameron Ewell committed 2024-09-13 19:46:34 -04:00
1 parent 12e151b4ec
commit a8729bd4e4
11 files changed
+377 -166

No files matched your search

-1
View File
@@ -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)
+64
View File
@@ -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;
}
}
}
}
+3
View File
@@ -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.
@@ -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.
+8 -15
View File
@@ -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);
+46 -85
View File
@@ -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<Texture2D>("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);
}
}
}
}
+3 -9
View File
@@ -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;
}
}
+46
View File
@@ -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
);
}
}
+144
View File
@@ -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<SpriteBatch, bool> Fld_BeginCalled = new("beginCalled", Bind_Private_Instance);
private static readonly FastField<SpriteBatch, SpriteSortMode> Fld_SortMode = new("sortMode", Bind_Private_Instance);
private static readonly FastField<SpriteBatch, BlendState> Fld_BlendState = new("blendState", Bind_Private_Instance);
private static readonly FastField<SpriteBatch, SamplerState> Fld_SamplerState = new("samplerState", Bind_Private_Instance);
private static readonly FastField<SpriteBatch, DepthStencilState> Fld_DepthStencilState = new("depthStencilState", Bind_Private_Instance);
private static readonly FastField<SpriteBatch, RasterizerState> Fld_RasterizerState = new("rasterizerState", Bind_Private_Instance);
private static readonly FastField<SpriteBatch, Matrix> Fld_TransformMatrix = new("transformMatrix", Bind_Private_Instance);
private static readonly FastField<SpriteBatch, Effect> Fld_CustomEffect = new("customEffect", Bind_Private_Instance);
/// <summary>
/// Sets a <see cref="SpriteBatch"/>'s <see cref="BlendState"/> arbitrarily.
/// </summary>
/// <param name="spriteBatch">The sprite batch.</param>
/// <param name="blendState">The blend state to use.</param>
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);
}
/// <summary>
/// Determines if a <see cref="SpriteBatch"/> is in a lock due to a <see cref="SpriteBatch.Begin"/> call.
/// </summary>
/// <param name="spriteBatch">The sprite batch to check.</param>
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();
}
}
}
/// <summary>
/// Starts SpriteBatch then Re-Begin batch with old settings when it's all done
/// </summary>
/// <param name="spriteBatch"></param>
/// <param name="sortMode"></param>
/// <param name="settings"></param>
/// <param name="effect"></param>
/// <param name="transformMatrix"></param>
/// <param name="batchCallback"></param>
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;
}
}
}
}
-55
View File
@@ -358,61 +358,6 @@ namespace CalamityMod
projectionMatrix = Matrix.CreateOrthographicOffCenter(0f, width * zoom.X, 0f, height * zoom.Y, 0f, 1f) * zoomScaleMatrix;
}
/// <summary>
/// Sets a <see cref="SpriteBatch"/>'s <see cref="BlendState"/> arbitrarily.
/// </summary>
/// <param name="spriteBatch">The sprite batch.</param>
/// <param name="blendState">The blend state to use.</param>
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);
/// <summary>
/// Determines if a <see cref="SpriteBatch"/> is in a lock due to a <see cref="SpriteBatch.Begin"/> call.
/// </summary>
/// <param name="spriteBatch">The sprite batch to check.</param>
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;
}
}
/// <summary>
/// Draws a line significantly more efficiently than <see cref="Utils.DrawLine(SpriteBatch, Vector2, Vector2, Color, Color, float)"/> using just one scaled line texture. Positions are automatically converted to screen coordinates.
/// </summary>
+62
View File
@@ -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<T, ValueType>(FieldInfo fieldInfo)
{
private Action<T, ValueType> _Setter = ReflectionHelper.CreateFieldSetter<T, ValueType>(fieldInfo);
private Func<T, ValueType> _Getter = ReflectionHelper.CreateFieldGetter<T, ValueType>(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<T, ValueType> CreateFieldSetter<T, ValueType>(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<T, ValueType>)setterMethod.CreateDelegate(typeof(Action<T, ValueType>));
}
public static Func<T, ValueType> CreateFieldGetter<T, ValueType>(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<T, ValueType>)getterMethod.CreateDelegate(typeof(Func<T, ValueType>));
}
}
}