Stream Gouge rework (rebased and resolved shader conflicts)

This commit is contained in:
DominicKarma authored and Cameron Ewell committed 2022-04-02 14:10:17 -04:00
1 parent 63244a7397
commit 58d5908bc1
10 files changed
+698 -323

No files matched your search

+3
View File
@@ -30,6 +30,7 @@ namespace CalamityMod.Effects
public static Effect DoGDisintegrationShader;
public static Effect ArtAttackTrailShader;
public static Effect CircularAoETelegraph;
public static Effect IntersectionClipShader;
public static Effect LocalLinearTransformationShader;
public static Effect BaseFusableParticleEdgeShader;
@@ -64,6 +65,7 @@ namespace CalamityMod.Effects
DoGDisintegrationShader = CalamityMod.Instance.GetEffect("Effects/DoGDisintegration");
ArtAttackTrailShader = CalamityMod.Instance.GetEffect("Effects/ArtAttackTrail");
CircularAoETelegraph = CalamityMod.Instance.GetEffect("Effects/CircularAoETelegraph");
IntersectionClipShader = CalamityMod.Instance.GetEffect("Effects/IntersectionClipShader");
LocalLinearTransformationShader = CalamityMod.Instance.GetEffect("Effects/LocalLinearTransformationShader");
BaseFusableParticleEdgeShader = CalamityMod.Instance.GetEffect("Effects/ParticleFusion/BaseFusableParticleEdgeShader");
@@ -96,6 +98,7 @@ namespace CalamityMod.Effects
GameShaders.Misc["CalamityMod:DoGDisintegration"] = new MiscShaderData(new Ref<Effect>(DoGDisintegrationShader), "DisintegrationPass");
GameShaders.Misc["CalamityMod:ArtAttack"] = new MiscShaderData(new Ref<Effect>(ArtAttackTrailShader), "TrailPass");
GameShaders.Misc["CalamityMod:CircularAoETelegraph"] = new MiscShaderData(new Ref<Effect>(CircularAoETelegraph), "TelegraphPass");
GameShaders.Misc["CalamityMod:IntersectionClip"] = new MiscShaderData(new Ref<Effect>(IntersectionClipShader), "ClipPass");
GameShaders.Misc["CalamityMod:LinearTransformation"] = new MiscShaderData(new Ref<Effect>(LocalLinearTransformationShader), "TransformationPass");
GameShaders.Misc["CalamityMod:BaseFusableParticleEdge"] = new MiscShaderData(new Ref<Effect>(BaseFusableParticleEdgeShader), "ParticlePass");
+39
View File
@@ -0,0 +1,39 @@
sampler uImage0 : register(s0);
sampler uImage1 : register(s1);
float3 uColor;
float3 uSecondaryColor;
float uOpacity : register(C0);
float uSaturation;
float uRotation;
float uTime;
float4 uSourceRect;
float2 uWorldPosition;
float uDirection;
float3 uLightSource;
float2 uImageSize0;
float2 uImageSize1;
float uIntersectionCutoffDirection;
float2 uIntersectionPosition;
float2 uIntersectionNormal;
float2 uSize;
float2 RotatedBy(float2 xy, float theta)
{
return float2(xy.x * cos(theta) + xy.y * sin(theta), xy.x * sin(theta) - xy.y * cos(theta));
}
float4 PixelShaderFunction(float4 sampleColor : COLOR0, float2 coords : TEXCOORD0) : COLOR0
{
float2 worldPos = uWorldPosition + RotatedBy(coords - 0.5, uRotation - 1.57) * uSize;
if (sign(dot(uIntersectionNormal, worldPos - uIntersectionPosition)) == uIntersectionCutoffDirection)
return 0;
return tex2D(uImage0, coords) * sampleColor;
}
technique Technique1
{
pass ClipPass
{
PixelShader = compile ps_2_0 PixelShaderFunction();
}
}
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

+14 -6
View File
@@ -11,29 +11,37 @@ namespace CalamityMod.Items.Weapons.Melee
{
public class StreamGouge : ModItem
{
public const int SpinTime = 45;
public const int SpearFireTime = 24;
public const int PortalLifetime = 30;
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Stream Gouge");
Tooltip.SetDefault("Fires an essence spear clone\n" +
"Ignores immunity frames");
Tooltip.SetDefault("Summons a portal that the spear crosses through\n" +
"Shortly after going through the portal, portals appear near the mouse that release copies of the spear's cutting edge\n" +
"Enemies hit by the copies create lacerations in space, revealing a cosmic background");
}
public override void SetDefaults()
{
item.width = 100;
item.damage = 112;
item.height = 100;
item.damage = 300;
item.melee = true;
item.noMelee = true;
item.useTurn = true;
item.noUseGraphic = true;
item.channel = true;
item.useAnimation = 19;
item.useStyle = ItemUseStyleID.HoldingOut;
item.useTime = 19;
item.useStyle = ItemUseStyleID.HoldingOut;
item.knockBack = 9.75f;
item.UseSound = SoundID.Item20;
item.autoReuse = true;
item.height = 100;
item.value = Item.buyPrice(1, 80, 0, 0);
item.value = CalamityGlobalItem.RarityDarkBlueBuyPrice;
item.rare = ItemRarityID.Red;
item.shoot = ModContent.ProjectileType<StreamGougeProj>();
item.shootSpeed = 15f;
+62
View File
@@ -0,0 +1,62 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Collections.Generic;
using System.Linq;
using Terraria;
using Terraria.Graphics.Shaders;
using Terraria.ModLoader;
namespace CalamityMod.Particles
{
public class StreamGougeParticleSet : BaseFusableParticleSet
{
public override float BorderSize => 3f;
public override bool BorderShouldBeSolid => false;
public override Color BorderColor => Color.Lerp(Color.DarkBlue, Color.Black, 0.75f) * 0.85f;
public override FusableParticleRenderLayer RenderLayer => FusableParticleRenderLayer.OverNPCsBeforeProjectiles;
public override List<Effect> BackgroundShaders => new List<Effect>()
{
GameShaders.Misc["CalamityMod:BaseFusableParticleEdge"].Shader,
};
public override List<Texture2D> BackgroundTextures => new List<Texture2D>()
{
ModContent.GetTexture("CalamityMod/ExtraTextures/ParticleBackgrounds/StreamGougeLayer"),
};
public override FusableParticle SpawnParticle(Vector2 center, float sizeStrength)
{
Particles.Add(new FusableParticle(center, sizeStrength));
return Particles.Last();
}
public override void UpdateBehavior(FusableParticle particle)
{
particle.Size = MathHelper.Clamp(particle.Size - 1f, 0f, 200f) * 0.98f;
}
public override void PrepareOptionalShaderData(Effect effect, int index)
{
switch (index)
{
// Background.
case 0:
Vector2 offset = Vector2.UnitX * Main.GlobalTime * 0.045f;
effect.Parameters["generalBackgroundOffset"].SetValue(offset);
effect.Parameters["upscaleFactor"].SetValue(Vector2.One * -0.3f);
break;
}
}
public override void DrawParticles()
{
Texture2D fusableParticleBase = ModContent.GetTexture("CalamityMod/ExtraTextures/FusableParticleBase");
foreach (FusableParticle particle in Particles)
{
Vector2 drawPosition = particle.Center - Main.screenPosition;
Vector2 origin = fusableParticleBase.Size() * 0.5f;
Vector2 scale = Vector2.One * particle.Size / fusableParticleBase.Size();
Main.spriteBatch.Draw(fusableParticleBase, drawPosition, null, Color.White, 0f, origin, scale, SpriteEffects.None, 0f);
}
}
}
}
+157 -28
View File
@@ -1,58 +1,187 @@
using CalamityMod.Buffs.DamageOverTime;
using CalamityMod.Items.Weapons.Melee;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.IO;
using Terraria;
using Terraria.Graphics.Shaders;
using Terraria.ModLoader;
using CalamityMod.Projectiles.BaseProjectiles;
namespace CalamityMod.Projectiles.Melee.Spears
{
public class StreamGougeProj : BaseSpearProjectile
public class StreamGougeProj : ModProjectile
{
public int Time;
public Player Owner => Main.player[projectile.owner];
public float SpinCompletion => Utils.InverseLerp(0f, StreamGouge.SpinTime, Time, true);
public ref float InitialDirection => ref projectile.ai[0];
public ref float SpinDirection => ref projectile.ai[1];
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Gouge");
DisplayName.SetDefault("Stream Gouge");
}
public override void SetDefaults()
{
projectile.width = 40;
projectile.aiStyle = 19;
projectile.melee = true;
projectile.timeLeft = 90;
projectile.height = 40;
projectile.penetrate = -1;
projectile.melee = true;
projectile.friendly = true;
projectile.hostile = false;
projectile.tileCollide = false;
projectile.ignoreWater = true;
projectile.penetrate = -1;
projectile.ownerHitCheck = true;
projectile.hide = true;
projectile.timeLeft = 90000;
projectile.MaxUpdates = 2;
projectile.usesLocalNPCImmunity = true;
projectile.localNPCHitCooldown = 5;
projectile.localNPCHitCooldown = projectile.MaxUpdates * 13;
}
public override float InitialSpeed => 3f;
public override float ForwardSpeed => 0.95f;
public override float ReelbackSpeed => 2.4f;
public override void PostDraw(SpriteBatch spriteBatch, Color lightColor)
public override void SendExtraAI(BinaryWriter writer)
{
spriteBatch.Draw(ModContent.GetTexture("CalamityMod/Projectiles/Melee/Spears/StreamGougeGlow"),
projectile.Center - Main.screenPosition,
null,
Color.White,
projectile.rotation,
Vector2.Zero,
1f,
SpriteEffects.None,
0f);
writer.Write(Time);
}
public override Action<Projectile> EffectBeforeReelback => (proj) =>
public override void ReceiveExtraAI(BinaryReader reader)
{
Projectile.NewProjectile(projectile.Center.X, projectile.Center.Y, projectile.velocity.X, projectile.velocity.Y,
ModContent.ProjectileType<EssenceBeam>(), projectile.damage * 4, projectile.knockBack, projectile.owner, 0f, 0f);
};
Time = reader.ReadInt32();
}
public override void AI()
{
// Play a strong slash sound on the first frame to accompany the spin.
if (Time == 0f)
Main.PlaySound(mod.GetLegacySoundSlot(SoundType.Custom, "Sounds/Custom/MeatySlash"), projectile.Center);
// Define the initial direction.
if (InitialDirection == 0f)
{
InitialDirection = projectile.velocity.ToRotation();
SpinDirection = Main.rand.NextBool().ToDirectionInt();
projectile.netUpdate = true;
}
else
{
float stabOffset = (float)Math.Sin(Time / 3f) * 15f;
float spearReach = MathHelper.Lerp(-10f, stabOffset + 90f, Utils.InverseLerp(0f, StreamGouge.SpearFireTime, Time - StreamGouge.SpinTime, true));
projectile.velocity = InitialDirection.ToRotationVector2() * spearReach;
}
// Define the current rotation.
projectile.rotation = (float)Math.Pow(SpinCompletion, 0.82) * MathHelper.Pi * SpinDirection * 4f + InitialDirection - MathHelper.PiOver4 + MathHelper.Pi;
// Manipulate player variables.
DeterminePlayerVariables();
// Create portals near the mouse once charged.
if (Main.myPlayer == projectile.owner && Time >= StreamGouge.SpinTime + StreamGouge.SpearFireTime && Time % 9f == 8f)
{
Vector2 portalSpawnPosition = Main.MouseWorld + Main.rand.NextVector2Unit() * Main.rand.NextFloat(50f, 140f);
Vector2 spearVelocity = (Main.MouseWorld - portalSpawnPosition).SafeNormalize(Vector2.UnitY);
Projectile.NewProjectile(portalSpawnPosition, spearVelocity, ModContent.ProjectileType<StreamGougePortal>(), projectile.damage, projectile.knockBack, projectile.owner);
}
Time++;
}
public void DeterminePlayerVariables()
{
bool spearStillInUse = Owner.channel && !Owner.noItems && !Owner.CCed;
Owner.direction = (Math.Cos(projectile.rotation - MathHelper.Pi + MathHelper.PiOver4) > 0f).ToDirectionInt();
Owner.heldProj = projectile.whoAmI;
Owner.itemTime = Owner.itemAnimation = 2;
Owner.itemRotation = CalamityUtils.WrapAngle90Degrees(MathHelper.WrapAngle(projectile.rotation - MathHelper.Pi + MathHelper.PiOver4));
projectile.Center = Owner.Center;
// Die if the spear is no longer in use.
if (!spearStillInUse)
projectile.Kill();
}
public void DrawPortal(SpriteBatch spriteBatch, Vector2 drawPosition, float opacity)
{
Texture2D portalTexture = ModContent.GetTexture("CalamityMod/Projectiles/Melee/StreamGougePortal");
Vector2 origin = portalTexture.Size() * 0.5f;
Color baseColor = Color.White;
float rotation = Main.GlobalTime * 6f;
// Black portal.
Color color = Color.Lerp(baseColor, Color.Black, 0.55f).MultiplyRGB(Color.DarkGray) * opacity;
spriteBatch.Draw(portalTexture, drawPosition, null, color, rotation, origin, projectile.scale * 1.2f, SpriteEffects.None, 0f);
spriteBatch.Draw(portalTexture, drawPosition, null, color, -rotation, origin, projectile.scale * 1.2f, SpriteEffects.None, 0f);
spriteBatch.SetBlendState(BlendState.Additive);
// Cyan portal.
color = Color.Lerp(baseColor, Color.Cyan, 0.55f) * opacity * 1.6f;
spriteBatch.Draw(portalTexture, drawPosition, null, color, rotation * 0.6f, origin, projectile.scale * 1.2f, SpriteEffects.None, 0f);
// Magenta portal.
color = Color.Lerp(baseColor, Color.Fuchsia, 0.55f) * opacity * 1.6f;
spriteBatch.Draw(portalTexture, drawPosition, null, color, rotation * -0.6f, origin, projectile.scale * 1.2f, SpriteEffects.None, 0f);
spriteBatch.SetBlendState(BlendState.AlphaBlend);
}
public override bool PreDraw(SpriteBatch spriteBatch, Color lightColor)
{
// Draw the spin smear texture.
if (SpinCompletion >= 0f && SpinCompletion < 1f)
{
Texture2D smear = ModContent.GetTexture("CalamityMod/Particles/SemiCircularSmear");
spriteBatch.EnterShaderRegion(BlendState.Additive);
float rotation = projectile.rotation - MathHelper.Pi / 5f;
if (SpinDirection == -1f)
rotation += MathHelper.Pi;
Color smearColor = Color.Fuchsia * CalamityUtils.Convert01To010(SpinCompletion) * 0.9f;
Vector2 smearOrigin = smear.Size() * 0.5f;
spriteBatch.Draw(smear, Owner.Center - Main.screenPosition, null, smearColor, rotation, smearOrigin, projectile.scale * 1.45f, 0, 0);
spriteBatch.ExitShaderRegion();
}
// Make the spear go through the portal.
float portalOpacity = Utils.InverseLerp(0.6f, 1f, SpinCompletion, true);
bool portalIsInteractable = portalOpacity >= 1f;
Vector2 portalDrawPosition = Owner.Center + InitialDirection.ToRotationVector2() * 130f - Main.screenPosition;
Texture2D texture = Main.projectileTexture[projectile.type];
if (portalIsInteractable)
{
spriteBatch.EnterShaderRegion();
Vector2 intersectionNormal = portalDrawPosition + Main.screenPosition - projectile.Center;
Vector2 worldOffset = projectile.rotation.ToRotationVector2() * -45f;
Vector2 intersectionOffset = (portalDrawPosition + Main.screenPosition - projectile.Center) * -1.5f;
GameShaders.Misc["CalamityMod:IntersectionClip"].Shader.Parameters["uIntersectionPosition"].SetValue(portalDrawPosition + intersectionOffset);
GameShaders.Misc["CalamityMod:IntersectionClip"].Shader.Parameters["uIntersectionNormal"].SetValue(intersectionNormal);
GameShaders.Misc["CalamityMod:IntersectionClip"].Shader.Parameters["uIntersectionCutoffDirection"].SetValue(-1f);
GameShaders.Misc["CalamityMod:IntersectionClip"].Shader.Parameters["uWorldPosition"].SetValue(projectile.Center - Main.screenPosition + worldOffset);
GameShaders.Misc["CalamityMod:IntersectionClip"].Shader.Parameters["uSize"].SetValue(texture.Size());
GameShaders.Misc["CalamityMod:IntersectionClip"].Shader.Parameters["uRotation"].SetValue(projectile.rotation);
GameShaders.Misc["CalamityMod:IntersectionClip"].Apply();
}
Vector2 drawPosition = projectile.Center - Main.screenPosition;
Vector2 origin = texture.Size() * 0.5f;
spriteBatch.Draw(texture, drawPosition, null, projectile.GetAlpha(lightColor), projectile.rotation, origin, 1f, 0, 0);
if (portalIsInteractable)
spriteBatch.ExitShaderRegion();
// Draw the portal once ready.
DrawPortal(spriteBatch, portalDrawPosition, portalOpacity);
return false;
}
public override void OnHitNPC(NPC target, int damage, float knockback, bool crit)
{
+123
View File
@@ -0,0 +1,123 @@
using CalamityMod.Items.Weapons.Melee;
using CalamityMod.Particles;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Graphics.Shaders;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Projectiles.Melee
{
public class StreamGougePortal : ModProjectile
{
public Vector2 SpearCenter => Vector2.Lerp(projectile.Center + projectile.velocity + projectile.velocity.SafeNormalize(Vector2.Zero) * 42f, projectile.Center, 1f - projectile.scale);
public ref float Time => ref projectile.ai[0];
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Portal");
}
public override void SetDefaults()
{
projectile.width = 14;
projectile.height = 14;
projectile.friendly = true;
projectile.melee = true;
projectile.tileCollide = false;
projectile.timeLeft = StreamGouge.PortalLifetime;
projectile.ignoreWater = true;
projectile.alpha = 255;
projectile.penetrate = -1;
projectile.MaxUpdates = 2;
projectile.usesLocalNPCImmunity = true;
projectile.localNPCHitCooldown = -1;
}
public override void AI()
{
// Play a slice sound when spawning.
if (projectile.localAI[0] == 0f)
{
Main.PlayTrackedSound(CalamityUtils.GetTrackableSound("Sounds/Custom/SwiftSlice"), projectile.Center);
projectile.localAI[0] = 1f;
}
float spearOutwardness = MathHelper.Lerp(4f, 52f, Utils.InverseLerp(0f, 18f, Time, true));
projectile.velocity = projectile.velocity.SafeNormalize(Vector2.UnitY) * spearOutwardness;
projectile.Opacity = Utils.InverseLerp(0f, 8f, Time, true) * Utils.InverseLerp(0f, 10f, projectile.timeLeft, true);
projectile.scale = projectile.Opacity;
projectile.rotation = projectile.velocity.ToRotation() + MathHelper.PiOver4;
Time++;
}
public override bool PreDraw(SpriteBatch spriteBatch, Color lightColor)
{
Texture2D texture = ModContent.GetTexture("CalamityMod/Items/Weapons/Melee/StreamGouge");
Vector2 spearDrawPosition = SpearCenter - Main.screenPosition;
Vector2 spearOrigin = texture.Size() * 0.5f;
Color spearColor = Main.hslToRgb(projectile.identity % 10f / 40f + 0.67f, 1f, 0.5f);
spearColor.A = 0;
for (int i = 0; i < 2; i++)
spriteBatch.Draw(texture, spearDrawPosition, null, spearColor * projectile.Opacity, projectile.rotation, spearOrigin, projectile.scale, 0, 0);
Texture2D portalTexture = ModContent.GetTexture("CalamityMod/Projectiles/Melee/StreamGougePortal");
Vector2 origin = portalTexture.Size() * 0.5f;
Color baseColor = Color.White;
Vector2 drawPosition = projectile.Center - Main.screenPosition;
float rotation = Main.GlobalTime * 6f + projectile.identity * 1.45f;
// Black portal.
Color color = Color.Lerp(baseColor, Color.Black, 0.55f).MultiplyRGB(Color.DarkGray) * projectile.Opacity;
spriteBatch.Draw(portalTexture, drawPosition, null, color, rotation, origin, projectile.scale * 1.2f, SpriteEffects.None, 0f);
spriteBatch.Draw(portalTexture, drawPosition, null, color, -rotation, origin, projectile.scale * 1.2f, SpriteEffects.None, 0f);
spriteBatch.SetBlendState(BlendState.Additive);
// Cyan portal.
color = Color.Lerp(baseColor, Color.Cyan, 0.55f) * projectile.Opacity * 1.4f;
spriteBatch.Draw(portalTexture, drawPosition, null, color, rotation * 0.6f, origin, projectile.scale * 1.2f, SpriteEffects.None, 0f);
// Magenta portal.
color = Color.Lerp(baseColor, Color.Fuchsia, 0.55f) * projectile.Opacity * 1.4f;
spriteBatch.Draw(portalTexture, drawPosition, null, color, rotation * -0.7f, origin, projectile.scale * 1.2f, SpriteEffects.None, 0f);
spriteBatch.SetBlendState(BlendState.AlphaBlend);
return false;
}
// Create impact and cosmic parallax particles when hitting enemies.
public override void OnHitNPC(NPC target, int damage, float knockback, bool crit)
{
Main.PlaySound(SoundID.Item74, target.Center);
if (Main.netMode == NetmodeID.Server)
return;
Color impactColor = Color.Lerp(Color.Cyan, Color.White, Main.rand.NextFloat(0.3f, 0.64f));
Vector2 impactPoint = Vector2.Lerp(projectile.Center, target.Center, 0.65f);
ImpactParticle impactParticle = new ImpactParticle(impactPoint, 0.1f, 20, Main.rand.NextFloat(0.4f, 0.5f), impactColor);
GeneralParticleHandler.SpawnParticle(impactParticle);
for (int i = 0; i < 20; i++)
{
Vector2 spawnPosition = target.Center + Main.rand.NextVector2Circular(30f, 30f);
FusableParticleManager.GetParticleSetByType<StreamGougeParticleSet>()?.SpawnParticle(spawnPosition, 60f);
float scale = MathHelper.Lerp(24f, 64f, CalamityUtils.Convert01To010(i / 19f));
spawnPosition = target.Center + projectile.velocity.SafeNormalize(Vector2.UnitY) * MathHelper.Lerp(-40f, 90f, i / 19f);
FusableParticleManager.GetParticleSetByType<StreamGougeParticleSet>()?.SpawnParticle(spawnPosition, scale);
}
}
public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox)
{
float _ = 0f;
Vector2 start = SpearCenter - projectile.velocity.SafeNormalize(Vector2.UnitY) * projectile.scale * 50f;
Vector2 end = SpearCenter + projectile.velocity.SafeNormalize(Vector2.UnitY) * projectile.scale * 50f;
return Collision.CheckAABBvLineCollision(targetHitbox.TopLeft(), targetHitbox.Size(), start, end, 15f, ref _);
}
public override bool ShouldUpdatePosition() => false;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 837 B

+300 -289
View File
@@ -24,168 +24,179 @@ using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;
using TerrariaAudio = Terraria.Audio;
namespace CalamityMod
{
public static partial class CalamityUtils
{
public static void DisplayLocalizedText(string key, Color? textColor = null)
{
// An attempt to bypass the need for a separate method and runtime/compile-time parameter
// constraints by using nulls for defaults.
if (!textColor.HasValue)
textColor = Color.White;
if (Main.netMode == NetmodeID.SinglePlayer)
Main.NewText(Language.GetTextValue(key), textColor.Value);
else if (Main.netMode == NetmodeID.Server)
NetMessage.BroadcastChatMessage(NetworkText.FromKey(key), textColor.Value);
}
// Yes, this method has a use that Utils.Swap does not; You cannot use refs on array indices.
// The CLR will not allow that. As such, a custom method must be used to achieve this.
/// <summary>
/// Swaps two array indices based on a temporary variable.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <param name="array">The array.</param>
/// <param name="index1">The first index to swap.</param>
/// <param name="index2">The second index to swap.</param>
public static void SwapArrayIndices<T>(ref T[] array, int index1, int index2)
{
T temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
public static T[] ShuffleArray<T>(T[] array, Random rand = null)
{
if (rand is null)
rand = new Random();
for (int i = array.Length; i > 0; --i)
{
int j = rand.Next(i);
T tempElement = array[j];
array[j] = array[i - 1];
array[i - 1] = tempElement;
}
return array;
}
public static T[,] ShaveOffEdge<T>(this T[,] array)
{
T[,] result = new T[array.GetLength(0) - 2, array.GetLength(1) - 2];
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
{
result[i, j] = array[i + 1, j + 1];
}
}
return result;
public static partial class CalamityUtils
{
/// <summary>
/// Gets an instance of a sound that is trackable when used in conjunction with <see cref="Main.PlayTrackedSound(TerrariaAudio.SoundStyle, Vector2)"/>.
/// </summary>
/// <param name="path">The path to the sound file.</param>
public static TerrariaAudio.CustomSoundStyle GetTrackableSound(string path)
{
return new TerrariaAudio.CustomSoundStyle(CalamityMod.Instance.GetSound(path), TerrariaAudio.SoundType.Sound);
}
/// <summary>
/// Retrieves all the colors from a <see cref="Texture2D"/> and returns them as a 2D <see cref="Color"/> array.
/// </summary>
/// <param name="texture">The texture to load.</param>
/// <returns></returns>
public static Color[,] GetColorsFromTexture(this Texture2D texture)
{
Color[] alignedColors = new Color[texture.Width * texture.Height];
texture.GetData(alignedColors); // Fills the color array with all the colors in the texture
public static void DisplayLocalizedText(string key, Color? textColor = null)
{
// An attempt to bypass the need for a separate method and runtime/compile-time parameter
// constraints by using nulls for defaults.
if (!textColor.HasValue)
textColor = Color.White;
Color[,] colors2D = new Color[texture.Width, texture.Height];
for (int x = 0; x < texture.Width; x++)
{
for (int y = 0; y < texture.Height; y++)
{
colors2D[x, y] = alignedColors[x + y * texture.Width];
}
}
return colors2D;
}
if (Main.netMode == NetmodeID.SinglePlayer)
Main.NewText(Language.GetTextValue(key), textColor.Value);
else if (Main.netMode == NetmodeID.Server)
NetMessage.BroadcastChatMessage(NetworkText.FromKey(key), textColor.Value);
}
public static string CombineStrings(params object[] args)
{
StringBuilder result = new StringBuilder(1024);
for (int i = 0; i < args.Length; ++i)
{
object o = args[i];
result.Append(o.ToString());
result.Append(' ');
}
return result.ToString();
}
// Yes, this method has a use that Utils.Swap does not; You cannot use refs on array indices.
// The CLR will not allow that. As such, a custom method must be used to achieve this.
/// <summary>
/// Determines if a list contains an entry of a specific type. Specifically intended to account for derived types.
/// </summary>
/// <typeparam name="T">The base type of the collection.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="type">The type to search for.</param>
public static bool ContainsType<T>(this IEnumerable<T> collection, Type type) => collection.Any(entry => entry.GetType() == type.GetType());
/// <summary>
/// Swaps two array indices based on a temporary variable.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <param name="array">The array.</param>
/// <param name="index1">The first index to swap.</param>
/// <param name="index2">The second index to swap.</param>
public static void SwapArrayIndices<T>(ref T[] array, int index1, int index2)
{
T temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
/// <summary>
/// Calculates the sound volume and panning for a sound which is played at the specified location in the game world.<br/>
/// Note that sound does not play on dedicated servers or during world generation.
/// </summary>
/// <param name="soundPos">The position the sound is emitting from. If either X or Y is -1, the sound does not fade with distance.</param>
/// <param name="ambient">Whether the sound is considered ambient, which makes it use the ambient sound slider in the options. Defaults to false.</param>
/// <returns>Volume and pan, in that order. Volume is always between 0 and 1. Pan is always between -1 and 1.</returns>
public static (float, float) CalculateSoundStats(Vector2 soundPos, bool ambient = false)
{
float volume = 0f;
float pan = 0f;
public static T[] ShuffleArray<T>(T[] array, Random rand = null)
{
if (rand is null)
rand = new Random();
if (soundPos.X == -1f || soundPos.Y == -1f)
volume = 1f;
else if (WorldGen.gen || Main.dedServ || Main.netMode == NetmodeID.Server)
volume = 0f;
else
{
float topLeftX = Main.screenPosition.X - Main.screenWidth * 2f;
float topLeftY = Main.screenPosition.Y - Main.screenHeight * 2f;
for (int i = array.Length; i > 0; --i)
{
int j = rand.Next(i);
T tempElement = array[j];
array[j] = array[i - 1];
array[i - 1] = tempElement;
}
return array;
}
// Sounds cannot be heard from more than ~2.5 screens away.
// This rectangle is 5x5 screens centered on the current screen center position.
Rectangle audibleArea = new Rectangle((int)topLeftX, (int)topLeftY, Main.screenWidth * 5, Main.screenHeight * 5);
Rectangle soundHitbox = new Rectangle((int)soundPos.X, (int)soundPos.Y, 1, 1);
Vector2 screenCenter = Main.screenPosition + new Vector2(Main.screenWidth * 0.5f, Main.screenHeight * 0.5f);
if (audibleArea.Intersects(soundHitbox))
{
pan = (soundPos.X - screenCenter.X) / (Main.screenWidth * 0.5f);
float dist = Vector2.Distance(soundPos, screenCenter);
volume = 1f - (dist / (Main.screenWidth * 1.5f));
}
}
public static T[,] ShaveOffEdge<T>(this T[,] array)
{
T[,] result = new T[array.GetLength(0) - 2, array.GetLength(1) - 2];
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
{
result[i, j] = array[i + 1, j + 1];
}
}
return result;
}
pan = MathHelper.Clamp(pan, -1f, 1f);
volume = MathHelper.Clamp(volume, 0f, 1f);
if (ambient)
volume = Main.gameInactive ? 0f : volume * Main.ambientVolume;
else
volume *= Main.soundVolume;
/// <summary>
/// Retrieves all the colors from a <see cref="Texture2D"/> and returns them as a 2D <see cref="Color"/> array.
/// </summary>
/// <param name="texture">The texture to load.</param>
/// <returns></returns>
public static Color[,] GetColorsFromTexture(this Texture2D texture)
{
Color[] alignedColors = new Color[texture.Width * texture.Height];
texture.GetData(alignedColors); // Fills the color array with all the colors in the texture
// This is actually done by vanilla. I guess if the sound volume gets corrupted during gameplay, you can't blast your eardrums out.
volume = MathHelper.Clamp(volume, 0f, 1f);
return (volume, pan);
}
Color[,] colors2D = new Color[texture.Width, texture.Height];
for (int x = 0; x < texture.Width; x++)
{
for (int y = 0; y < texture.Height; y++)
{
colors2D[x, y] = alignedColors[x + y * texture.Width];
}
}
return colors2D;
}
/// <summary>
/// Convenience function to utilize CalculateSoundStats immediately on an existing sound effect.<br/>
/// This allows updating a looping sound every single frame to have the correct volume and pan, even if the player drags the audio sliders around.
/// </summary>
/// <param name="sfx">The SoundEffectInstance which is having its values updated.</param>
/// <param name="soundPos">The position the sound is emitting from. If either X or Y is -1, the sound does not fade with distance.</param>
/// <param name="ambient">Whether the sound is considered ambient, which makes it use the ambient sound slider in the options. Defaults to false.</param>
public static void ApplySoundStats(ref SoundEffectInstance sfx, Vector2 soundPos, bool ambient = false)
{
if (sfx is null || sfx.IsDisposed)
return;
(sfx.Volume, sfx.Pan) = CalculateSoundStats(soundPos, ambient);
}
public static string CombineStrings(params object[] args)
{
StringBuilder result = new StringBuilder(1024);
for (int i = 0; i < args.Length; ++i)
{
object o = args[i];
result.Append(o.ToString());
result.Append(' ');
}
return result.ToString();
}
/// <summary>
/// Determines if a list contains an entry of a specific type. Specifically intended to account for derived types.
/// </summary>
/// <typeparam name="T">The base type of the collection.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="type">The type to search for.</param>
public static bool ContainsType<T>(this IEnumerable<T> collection, Type type) => collection.Any(entry => entry.GetType() == type.GetType());
/// <summary>
/// Calculates the sound volume and panning for a sound which is played at the specified location in the game world.<br/>
/// Note that sound does not play on dedicated servers or during world generation.
/// </summary>
/// <param name="soundPos">The position the sound is emitting from. If either X or Y is -1, the sound does not fade with distance.</param>
/// <param name="ambient">Whether the sound is considered ambient, which makes it use the ambient sound slider in the options. Defaults to false.</param>
/// <returns>Volume and pan, in that order. Volume is always between 0 and 1. Pan is always between -1 and 1.</returns>
public static (float, float) CalculateSoundStats(Vector2 soundPos, bool ambient = false)
{
float volume = 0f;
float pan = 0f;
if (soundPos.X == -1f || soundPos.Y == -1f)
volume = 1f;
else if (WorldGen.gen || Main.dedServ || Main.netMode == NetmodeID.Server)
volume = 0f;
else
{
float topLeftX = Main.screenPosition.X - Main.screenWidth * 2f;
float topLeftY = Main.screenPosition.Y - Main.screenHeight * 2f;
// Sounds cannot be heard from more than ~2.5 screens away.
// This rectangle is 5x5 screens centered on the current screen center position.
Rectangle audibleArea = new Rectangle((int)topLeftX, (int)topLeftY, Main.screenWidth * 5, Main.screenHeight * 5);
Rectangle soundHitbox = new Rectangle((int)soundPos.X, (int)soundPos.Y, 1, 1);
Vector2 screenCenter = Main.screenPosition + new Vector2(Main.screenWidth * 0.5f, Main.screenHeight * 0.5f);
if (audibleArea.Intersects(soundHitbox))
{
pan = (soundPos.X - screenCenter.X) / (Main.screenWidth * 0.5f);
float dist = Vector2.Distance(soundPos, screenCenter);
volume = 1f - (dist / (Main.screenWidth * 1.5f));
}
}
pan = MathHelper.Clamp(pan, -1f, 1f);
volume = MathHelper.Clamp(volume, 0f, 1f);
if (ambient)
volume = Main.gameInactive ? 0f : volume * Main.ambientVolume;
else
volume *= Main.soundVolume;
// This is actually done by vanilla. I guess if the sound volume gets corrupted during gameplay, you can't blast your eardrums out.
volume = MathHelper.Clamp(volume, 0f, 1f);
return (volume, pan);
}
/// <summary>
/// Convenience function to utilize CalculateSoundStats immediately on an existing sound effect.<br/>
/// This allows updating a looping sound every single frame to have the correct volume and pan, even if the player drags the audio sliders around.
/// </summary>
/// <param name="sfx">The SoundEffectInstance which is having its values updated.</param>
/// <param name="soundPos">The position the sound is emitting from. If either X or Y is -1, the sound does not fade with distance.</param>
/// <param name="ambient">Whether the sound is considered ambient, which makes it use the ambient sound slider in the options. Defaults to false.</param>
public static void ApplySoundStats(ref SoundEffectInstance sfx, Vector2 soundPos, bool ambient = false)
{
if (sfx is null || sfx.IsDisposed)
return;
(sfx.Volume, sfx.Pan) = CalculateSoundStats(soundPos, ambient);
}
/// <summary>
/// Method to change the volume of a sound without having to manually do a nullcheck or having to clamp it down to between 0 and 1
@@ -200,148 +211,148 @@ namespace CalamityMod
}
public static void StartRain(bool torrentialTear = false, bool maxSeverity = false)
{
int num = 86400;
int num2 = num / 24;
Main.rainTime = Main.rand.Next(num2 * 8, num);
if (Main.rand.NextBool(3))
{
Main.rainTime += Main.rand.Next(0, num2);
}
if (Main.rand.NextBool(4))
{
Main.rainTime += Main.rand.Next(0, num2 * 2);
}
if (Main.rand.NextBool(5))
{
Main.rainTime += Main.rand.Next(0, num2 * 2);
}
if (Main.rand.NextBool(6))
{
Main.rainTime += Main.rand.Next(0, num2 * 3);
}
if (Main.rand.NextBool(7))
{
Main.rainTime += Main.rand.Next(0, num2 * 4);
}
if (Main.rand.NextBool(8))
{
Main.rainTime += Main.rand.Next(0, num2 * 5);
}
float num3 = 1f;
if (Main.rand.NextBool(2))
{
num3 += 0.05f;
}
if (Main.rand.NextBool(3))
{
num3 += 0.1f;
}
if (Main.rand.NextBool(4))
{
num3 += 0.15f;
}
if (Main.rand.NextBool(5))
{
num3 += 0.2f;
}
Main.rainTime = (int)(Main.rainTime * num3);
Main.raining = true;
if (torrentialTear)
TorrentialTear.AdjustRainSeverity(maxSeverity);
CalamityNetcode.SyncWorld();
}
{
int num = 86400;
int num2 = num / 24;
Main.rainTime = Main.rand.Next(num2 * 8, num);
if (Main.rand.NextBool(3))
{
Main.rainTime += Main.rand.Next(0, num2);
}
if (Main.rand.NextBool(4))
{
Main.rainTime += Main.rand.Next(0, num2 * 2);
}
if (Main.rand.NextBool(5))
{
Main.rainTime += Main.rand.Next(0, num2 * 2);
}
if (Main.rand.NextBool(6))
{
Main.rainTime += Main.rand.Next(0, num2 * 3);
}
if (Main.rand.NextBool(7))
{
Main.rainTime += Main.rand.Next(0, num2 * 4);
}
if (Main.rand.NextBool(8))
{
Main.rainTime += Main.rand.Next(0, num2 * 5);
}
float num3 = 1f;
if (Main.rand.NextBool(2))
{
num3 += 0.05f;
}
if (Main.rand.NextBool(3))
{
num3 += 0.1f;
}
if (Main.rand.NextBool(4))
{
num3 += 0.15f;
}
if (Main.rand.NextBool(5))
{
num3 += 0.2f;
}
Main.rainTime = (int)(Main.rainTime * num3);
Main.raining = true;
if (torrentialTear)
TorrentialTear.AdjustRainSeverity(maxSeverity);
CalamityNetcode.SyncWorld();
}
public static void StartSandstorm()
{
typeof(Terraria.GameContent.Events.Sandstorm).GetMethod("StartSandstorm", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, null);
}
public static void StartSandstorm()
{
typeof(Terraria.GameContent.Events.Sandstorm).GetMethod("StartSandstorm", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, null);
}
public static void StopSandstorm()
{
Terraria.GameContent.Events.Sandstorm.Happening = false;
}
public static void StopSandstorm()
{
Terraria.GameContent.Events.Sandstorm.Happening = false;
}
public static void AddWithCondition<T>(this List<T> list, T type, bool condition)
{
if (condition)
list.Add(type);
}
public static void AddWithCondition<T>(this List<T> list, T type, bool condition)
{
if (condition)
list.Add(type);
}
public static int SecondsToFrames(int seconds) => seconds * 60;
public static int SecondsToFrames(float seconds) => (int)(seconds * 60);
public static int SecondsToFrames(int seconds) => seconds * 60;
public static int SecondsToFrames(float seconds) => (int)(seconds * 60);
/// <summary>
/// Call this function to spawn explosion clouds at the specified location. Good for when NPCs or projectiles die and need to explode.
/// </summary>
/// <param name="goreSource">The spot to spawn the explosion clouds</param>
/// <param name="goreAmt">Number of times it loops to spawn gores</param>
public static void ExplosionGores(Vector2 goreSource, int goreAmt)
{
Vector2 source = new Vector2(goreSource.X - 24f, goreSource.Y - 24f);
for (int goreIndex = 0; goreIndex < goreAmt; goreIndex++)
{
float velocityMult = 0.33f;
if (goreIndex < (goreAmt / 3))
{
velocityMult = 0.66f;
}
if (goreIndex >= (2 * goreAmt / 3))
{
velocityMult = 1f;
}
Mod mod = ModContent.GetInstance<CalamityMod>();
int type = Main.rand.Next(61, 64);
int smoke = Gore.NewGore(source, default, type, 1f);
Gore gore = Main.gore[smoke];
gore.velocity *= velocityMult;
gore.velocity.X += 1f;
gore.velocity.Y += 1f;
type = Main.rand.Next(61, 64);
smoke = Gore.NewGore(source, default, type, 1f);
gore = Main.gore[smoke];
gore.velocity *= velocityMult;
gore.velocity.X -= 1f;
gore.velocity.Y += 1f;
type = Main.rand.Next(61, 64);
smoke = Gore.NewGore(source, default, type, 1f);
gore = Main.gore[smoke];
gore.velocity *= velocityMult;
gore.velocity.X += 1f;
gore.velocity.Y -= 1f;
type = Main.rand.Next(61, 64);
smoke = Gore.NewGore(source, default, type, 1f);
gore = Main.gore[smoke];
gore.velocity *= velocityMult;
gore.velocity.X -= 1f;
gore.velocity.Y -= 1f;
}
}
/// <summary>
/// Call this function to spawn explosion clouds at the specified location. Good for when NPCs or projectiles die and need to explode.
/// </summary>
/// <param name="goreSource">The spot to spawn the explosion clouds</param>
/// <param name="goreAmt">Number of times it loops to spawn gores</param>
public static void ExplosionGores(Vector2 goreSource, int goreAmt)
{
Vector2 source = new Vector2(goreSource.X - 24f, goreSource.Y - 24f);
for (int goreIndex = 0; goreIndex < goreAmt; goreIndex++)
{
float velocityMult = 0.33f;
if (goreIndex < (goreAmt / 3))
{
velocityMult = 0.66f;
}
if (goreIndex >= (2 * goreAmt / 3))
{
velocityMult = 1f;
}
Mod mod = ModContent.GetInstance<CalamityMod>();
int type = Main.rand.Next(61, 64);
int smoke = Gore.NewGore(source, default, type, 1f);
Gore gore = Main.gore[smoke];
gore.velocity *= velocityMult;
gore.velocity.X += 1f;
gore.velocity.Y += 1f;
type = Main.rand.Next(61, 64);
smoke = Gore.NewGore(source, default, type, 1f);
gore = Main.gore[smoke];
gore.velocity *= velocityMult;
gore.velocity.X -= 1f;
gore.velocity.Y += 1f;
type = Main.rand.Next(61, 64);
smoke = Gore.NewGore(source, default, type, 1f);
gore = Main.gore[smoke];
gore.velocity *= velocityMult;
gore.velocity.X += 1f;
gore.velocity.Y -= 1f;
type = Main.rand.Next(61, 64);
smoke = Gore.NewGore(source, default, type, 1f);
gore = Main.gore[smoke];
gore.velocity *= velocityMult;
gore.velocity.X -= 1f;
gore.velocity.Y -= 1f;
}
}
public static bool WithinBounds(this int index, int cap) => index >= 0 && index < cap;
public static bool WithinBounds(this int index, int cap) => index >= 0 && index < cap;
/// Clamps the distance between vectors via normalization.
/// </summary>
/// <param name="start">The starting point.</param>
/// <param name="end">The ending point.</param>
/// <param name="maxDistance">The maximum possible distance between the two vectors before they get clamped.</param>
public static void DistanceClamp(ref Vector2 start, ref Vector2 end, float maxDistance)
{
if (Vector2.Distance(end, start) > maxDistance)
{
end = start + Vector2.Normalize(end - start) * maxDistance;
}
}
/// Clamps the distance between vectors via normalization.
/// </summary>
/// <param name="start">The starting point.</param>
/// <param name="end">The ending point.</param>
/// <param name="maxDistance">The maximum possible distance between the two vectors before they get clamped.</param>
public static void DistanceClamp(ref Vector2 start, ref Vector2 end, float maxDistance)
{
if (Vector2.Distance(end, start) > maxDistance)
{
end = start + Vector2.Normalize(end - start) * maxDistance;
}
}
public static void ChangeTime(bool changeToDay)
{
Main.time = 0D;
Main.dayTime = changeToDay;
CalamityNetcode.SyncWorld();
}
public static void ChangeTime(bool changeToDay)
{
Main.time = 0D;
Main.dayTime = changeToDay;
CalamityNetcode.SyncWorld();
}
public static int GetBannerItem(int style)
{
public static int GetBannerItem(int style)
{
int item = -1;
switch (style)
{
@@ -729,11 +740,11 @@ namespace CalamityMod
default:
break;
}
return item;
}
return item;
}
public static int GetBannerNPC(int style)
{
public static int GetBannerNPC(int style)
{
int npc = -1;
switch (style)
{
@@ -1118,7 +1129,7 @@ namespace CalamityMod
default:
break;
}
return npc;
}
}
return npc;
}
}
}