Fish Boids

- Implemented new fish boids that swim across the Sunken Menu Screen idly
This commit is contained in:
fryzahh authored and Cameron Ewell committed 2025-05-24 18:30:39 -04:00
1 parent f2fa8537be
commit b17b575399
2 files changed
+405 -37

No files matched your search

+103 -37
View File
@@ -1,8 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ReLogic.Content;
using ReLogic.Threading;
using Terraria;
using Terraria.Graphics.Shaders;
using Terraria.ID;
@@ -35,11 +38,11 @@ namespace CalamityMod.MainMenu
}
}
public static List<Bubble> Bubbles
{
get;
internal set;
} = new();
public static List<Bubble> Bubbles { get; private set; } = [];
public static List<SunkenFishBoid> Fishes { get; private set; } = [];
public int MaxBoids = 120;
public float remixLogoRotation = 0f;
public override string DisplayName => "Calamity Style - Sunken";
@@ -53,8 +56,32 @@ namespace CalamityMod.MainMenu
public override ModSurfaceBackgroundStyle MenuBackgroundStyle => ModContent.GetInstance<NullSurfaceBackground>();
// Before drawing the logo, draw the entire Calamity background. This way, the typical parallax background is skipped entirely.
public override bool PreDrawLogo(SpriteBatch spriteBatch, ref Vector2 logoDrawCenter, ref float logoRotation, ref float logoScale, ref Color drawColor)
{
// Draw the main background for the menu.
DrawMenuBackground(spriteBatch);
// Draw the fish boids passively swimming around the menu.
DrawFishes(spriteBatch);
// Draw the bubbles rising from the bottom of the screen.
DrawBubbles(spriteBatch);
// Draw the light rays at the top of the screen.
DrawLightRays(spriteBatch);
// Draw the logo.
DrawLogo(spriteBatch, ref logoDrawCenter, ref logoRotation, ref logoScale, ref drawColor);
return false;
}
private static Color SelectBubbleColor()
{
return Color.Lerp(Color.Lerp(Color.MediumSlateBlue, Color.DarkBlue, 0.3f), Color.Lerp(Color.MediumTurquoise, Color.PaleTurquoise, Main.rand.NextFloat()), Main.rand.NextFloat());
}
private void DrawMenuBackground(SpriteBatch spriteBatch)
{
Texture2D backgroundTexture = ModContent.Request<Texture2D>("CalamityMod/MainMenu/SunkenMenuBackground").Value;
@@ -96,9 +123,12 @@ namespace CalamityMod.MainMenu
spriteBatch.Draw(backgroundTexture, drawOffset, null, Color.White, 0f, Vector2.Zero, scale, SpriteEffects.None, 0f);
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, Main.Rasterizer, null, Main.UIScaleMatrix);
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Main.UIScaleMatrix);
}
private void DrawLightRays(SpriteBatch spriteBatch)
{
// Draw rays shining down from the top of the screen.
MiscShaderData underwaterRaysShader = GameShaders.Misc["CalamityMod:UnderwaterRays"];
Asset<Texture2D> underwaterRayTexture = ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/GreyscaleGradients/Pebbles");
@@ -120,12 +150,41 @@ namespace CalamityMod.MainMenu
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, Main.Rasterizer, null, Main.UIScaleMatrix);
}
static Color selectBubbleColor()
private void DrawLogo(SpriteBatch spriteBatch, ref Vector2 logoDrawCenter, ref float logoRotation, ref float logoScale, ref Color drawColor)
{
// Set the logo draw color to be white and the time to be noon
// This is because there is not a day/night cycle in this menu, and changing colors would look bad
drawColor = Color.White;
Main.time = 27000;
Main.dayTime = true;
// Adjust rotation based on secret seeds; only Drunk world and Remix touch this, with GFB leeching off those two
// Standard rotation is none; Drunk world makes it spin out, so it can use the vanilla rotation due to disappearing
// Remix makes it flip upside down, and in GFB it will spin forever
if (WorldGen.remixWorldGen)
{
return Color.Lerp(Color.Lerp(Color.MediumSlateBlue, Color.DarkBlue, 0.3f), Color.Lerp(Color.MediumTurquoise, Color.PaleTurquoise, Main.rand.NextFloat()), Main.rand.NextFloat());
remixLogoRotation += MathHelper.Pi / 50f;
if (remixLogoRotation >= MathHelper.Pi && !WorldGen.everythingWorldGen)
remixLogoRotation = MathHelper.Pi;
}
else
remixLogoRotation = 0f;
float rotationSecretSeedAdjusted = WorldGen.remixWorldGen ? remixLogoRotation : WorldGen.drunkWorldGen ? logoRotation : 0f;
// Draw the logo using a different spritebatch blending setting so it doesn't have a horrible yellow glow
Vector2 drawPos = new Vector2(Main.screenWidth / 2f, 100f);
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, Main.Rasterizer, null, Main.UIScaleMatrix);
spriteBatch.Draw(Logo.Value, drawPos, null, drawColor, rotationSecretSeedAdjusted, Logo.Value.Size() * 0.5f, WorldGen.drunkWorldGen ? logoScale : 1f, SpriteEffects.None, 0f);
spriteBatch.Draw(LogoWater.Value, drawPos, null, new Color(255, 255, 255, 0.5f) * 0.7f, rotationSecretSeedAdjusted, Logo.Value.Size() * 0.5f, WorldGen.drunkWorldGen ? logoScale : 1f, SpriteEffects.None, 0f);
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Main.UIScaleMatrix);
}
private void DrawBubbles(SpriteBatch spriteBatch)
{
// Randomly add bubbles.
for (int i = 0; i < 3; i++)
{
@@ -135,7 +194,7 @@ namespace CalamityMod.MainMenu
float depth = Main.rand.NextFloat(1.8f, 5f);
Vector2 startingPosition = new Vector2(Main.screenWidth * Main.rand.NextFloat(-0.1f, 1.1f), Main.screenHeight * 1.05f);
Vector2 startingVelocity = -Vector2.UnitY.RotatedBy(Main.rand.NextFloat(-0.4f, 0.4f)) * 2f;
Color bubbleColor = selectBubbleColor();
Color bubbleColor = SelectBubbleColor();
Bubbles.Add(new Bubble(lifetime, Bubbles.Count, depth, bubbleColor, startingPosition, startingVelocity));
}
}
@@ -164,35 +223,42 @@ namespace CalamityMod.MainMenu
Vector2 drawPosition = Bubbles[i].Center;
spriteBatch.Draw(bubbleTexture, drawPosition, null, Bubbles[i].DrawColor, Main.rand.NextFloat(0f, 90f), bubbleTexture.Size() * 0.5f, Bubbles[i].Scale, 0, 0f);
}
}
// Set the logo draw color to be white and the time to be noon
// This is because there is not a day/night cycle in this menu, and changing colors would look bad
drawColor = Color.White;
Main.time = 27000;
Main.dayTime = true;
// Adjust rotation based on secret seeds; only Drunk world and Remix touch this, with GFB leeching off those two
// Standard rotation is none; Drunk world makes it spin out, so it can use the vanilla rotation due to disappearing
// Remix makes it flip upside down, and in GFB it will spin forever
if (WorldGen.remixWorldGen)
private void DrawFishes(SpriteBatch spriteBatch)
{
// Generate random schools of fishes.
if (Main.rand.NextBool(14) && Fishes.Count < MaxBoids)
{
remixLogoRotation += MathHelper.Pi / 50f;
if (remixLogoRotation >= MathHelper.Pi && !WorldGen.everythingWorldGen)
remixLogoRotation = MathHelper.Pi;
}
else
remixLogoRotation = 0f;
float rotationSecretSeedAdjusted = WorldGen.remixWorldGen ? remixLogoRotation : WorldGen.drunkWorldGen ? logoRotation : 0f;
int schoolCount = Main.rand.Next(1, 4);
for (int i = 0; i < schoolCount; i++)
{
int depth = Main.rand.Next(1, 4);
int lifetime = Main.rand.Next(1200, 1800);
float scale = Main.rand.NextFloat(0.8f, 1.2f);
Vector2 schoolSpawnPosition = new(Main.screenWidth * Main.rand.NextFloat(-0.1f, 1.1f) * depth, Main.screenHeight * Main.rand.NextFloat(-0.1f, 1.1f) * depth);
// Draw the logo using a different spritebatch blending setting so it doesn't have a horrible yellow glow
Vector2 drawPos = new Vector2(Main.screenWidth / 2f, 100f);
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, Main.Rasterizer, null, Main.UIScaleMatrix);
spriteBatch.Draw(Logo.Value, drawPos, null, drawColor, rotationSecretSeedAdjusted, Logo.Value.Size() * 0.5f, WorldGen.drunkWorldGen ? logoScale : 1f, SpriteEffects.None, 0f);
spriteBatch.Draw(LogoWater.Value, drawPos, null, new Color(255, 255, 255, 0.5f) * 0.7f, rotationSecretSeedAdjusted, Logo.Value.Size() * 0.5f, WorldGen.drunkWorldGen ? logoScale : 1f, SpriteEffects.None, 0f);
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, Main.Rasterizer, null, Main.UIScaleMatrix);
return false;
int fishCount = Main.rand.Next(3, 11);
for (int j = 0; j < fishCount; j++)
{
Vector2 individualFishSpawnPosition = schoolSpawnPosition + Main.rand.NextVector2Circular(100f, 100f);
SunkenFishBoid fish = new(schoolSpawnPosition, scale, lifetime, depth);
Fishes.Add(fish);
}
}
}
// Remove expired fish.
Fishes.RemoveAll(f => f.Time >= f.Lifetime);
// Update all fish.
for (int i = 0; i < Fishes.Count; i++)
Fishes[i].Update();
// Draw all fish in an order based on their depth.
var fishesByDepth = Fishes.OrderByDescending(f => f.Depth).ToList();
foreach (SunkenFishBoid fish in fishesByDepth)
fish.Draw(spriteBatch);
}
}
}
+302
View File
@@ -0,0 +1,302 @@
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Audio;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.MainMenu
{
public class SunkenFishBoid
{
// -- GENERAL VARIABLES FOR DEFINING GENERAL BEHAVIOR AND FUNCTIONALITY FOR THE FISH ENTITIES --
public enum FishType
{
SeaMinnow,
PolypPanasea,
PrismaticGuppy1,
PrismaticGuppy2,
PrismaticGuppy3,
}
public string[] SeaMinnowTextureNames =
[
"SeaMinnow",
"AlphaSeaMinnow",
];
public string[] PolypPanaseaTextureNames =
[
"PolypPanasea",
"PolypPanaseaGreen",
"PolypPanaseaPurple",
"PolypPanaseaRadiant",
"PolypPanaseaTurquoise",
"PolypPanaseaGoldCoated",
"PolypPanaseaGreenCoated",
"PolypPanaseaPurpleCoated",
"PolypPanaseaRadiantCoated",
"PolypPanaseaRedCoated",
"PolypPanaseaTurquoiseCoated",
];
public string[] PrismaticGuppyTextureNames_1 =
[
"PrismaticGuppy",
"PrismaticGuppyGreen",
"PrismaticGuppyPink",
"PrismaticGuppyRadiant",
];
public string[] PrismaticGuppyTextureNames_2 =
[
"PrismaticGuppy2",
"PrismaticGuppyGreen2",
"PrismaticGuppyPink2",
"PrismaticGuppyRadiant2",
];
public string[] PrismaticGuppyTextureNames_3 =
[
"PrismaticGuppy3",
"PrismaticGuppyGreen3",
"PrismaticGuppyPink3",
"PrismaticGuppyRadiant3",
];
public int Time;
public int Lifetime;
public int Depth;
public int CurrentFrame;
public int MaxFrames;
public Vector2 Position;
public Vector2 Velocity;
public float Scale;
public float StoredScale;
public float Rotation;
public float Opacity;
public float PassiveMovementTimer;
public Vector2 PassiveMovementVector;
public float PassiveMovementSpeed;
public float MaxSpeed = 2f;
public FishType SelectedFishType;
public int FishTextureIndex = -1;
public bool Initialized = false;
// -- BOID ALOGORITHM SPECIFIC VARIABLES --
// 19MAY2025: fryzahh:
// Coefficients to control how strongly each of the Boid Algos affect the movement of each boid.
// Higher values will lead to sharper flocking AI, but movement might be a little choppier.
// Please beware of this if you ever change these values.
public float CohesionCoefficient = 0.015f;
public float AlignmentCoefficient = 0.035f;
public float SeparationCoefficient = 0.055f;
public float MaxRadiusFromOtherFish = 75f;
public float MaxDetectionRadius = 125f;
/// <summary>
/// The ratio of how much time a fish has left to live before despawning.
/// </summary>
public float LifetimeInterpolant => Time / (float)Lifetime;
/// <summary>
/// Whether or not this fish boid is any of the Prismatic Guppy variants. Used for allowing allow Prismatic Guppies to school with each other.
/// </summary>
public bool IsAPrismaticGuppy => SelectedFishType == FishType.PrismaticGuppy1 || SelectedFishType == FishType.PrismaticGuppy2 || SelectedFishType == FishType.PrismaticGuppy3;
public SunkenFishBoid(Vector2 position, float scale, int lifetime, int depth)
{
Position = position;
StoredScale = scale;
Lifetime = lifetime;
Depth = depth;
SelectedFishType = (FishType)Main.rand.Next(0, 5);
}
public void Update()
{
if (!Initialized)
{
// Select the correct texture index for the different types of fish textures.
if (SelectedFishType == FishType.SeaMinnow)
FishTextureIndex = Main.rand.Next(SeaMinnowTextureNames.Length);
if (SelectedFishType == FishType.PolypPanasea)
FishTextureIndex = Main.rand.Next(PolypPanaseaTextureNames.Length);
if (SelectedFishType == FishType.PrismaticGuppy1 || SelectedFishType == FishType.PrismaticGuppy2 || SelectedFishType == FishType.PrismaticGuppy3)
FishTextureIndex = Main.rand.Next(PrismaticGuppyTextureNames_1.Length);
// Select the correct amount of animation frames each texture has based on the fish type.
if (SelectedFishType == FishType.SeaMinnow)
MaxFrames = 8;
if (SelectedFishType == FishType.PolypPanasea)
MaxFrames = 6;
if (SelectedFishType == FishType.PrismaticGuppy1)
MaxFrames = 6;
if (SelectedFishType == FishType.PrismaticGuppy2)
MaxFrames = 4;
if (SelectedFishType == FishType.PrismaticGuppy3)
MaxFrames = 5;
Initialized = true;
}
// Don't run anything if the previous two variables haven't been intialized properly.
if (!Initialized)
return;
// Scale up and out accordingly depending on the remaining lifetime of the fish.
if (LifetimeInterpolant < 0.07f)
{
Scale = MathHelper.Lerp(0f, StoredScale, LifetimeInterpolant / 0.07f);
Opacity = MathHelper.Lerp(0f, 1f, LifetimeInterpolant / 0.07f);
}
else if (LifetimeInterpolant > 0.9f)
{
Scale = MathHelper.Lerp(StoredScale, 0f, (LifetimeInterpolant - 0.9f) / 0.1f);
Opacity = MathHelper.Lerp(1f, 0f, (LifetimeInterpolant - 0.9f) / 0.1f);
}
// Rotate towards the movement direction.
Rotation = Velocity.ToRotation();
// Animate.
if (Time % 6 == 0)
CurrentFrame = (CurrentFrame + 1) % MaxFrames;
// Perform all Boids Behavior.
DoBoidsBehavior();
// Move and swim around idly.
PassiveMovementTimer--;
if (PassiveMovementTimer <= 0f)
{
PassiveMovementSpeed = Main.rand.NextFloat(0.05f, 1.45f);
PassiveMovementVector.X = Main.rand.NextFloat(-100f, 101f);
PassiveMovementVector.Y = Main.rand.NextFloat(-100f, 101f);
PassiveMovementTimer = Main.rand.Next(120, 180);
}
float moveSpeed = PassiveMovementSpeed / PassiveMovementVector.Length();
Velocity = Vector2.Lerp(Velocity, PassiveMovementVector * moveSpeed, 0.01f);
// Make fishes closest to the screen swim away from the mouse cursor if it's nearby.
float distanceFromCursor = Vector2.Distance(Position, Main.MouseScreen);
if (distanceFromCursor < 100f && Depth <= 1)
{
float distanceInterpolant = Utils.GetLerpValue(100f, 20f, distanceFromCursor, true);
Velocity += Position.DirectionTo(Main.MouseScreen).SafeNormalize(Vector2.UnitY) * distanceInterpolant * -0.8f;
}
Velocity = Velocity.ClampMagnitude(0f, 1.45f);
Position += Velocity;
Time++;
}
public void DoBoidsBehavior()
{
Vector2 cohesion = Vector2.Zero;
Vector2 alignment = Vector2.Zero;
Vector2 separation = Vector2.Zero;
int totalSchoolMembers = 0;
float detetctionRadiusSquared = MathF.Pow(MaxDetectionRadius, 2f);
float separationDistanceSquared = MathF.Pow(MaxRadiusFromOtherFish, 2f);
List<SunkenFishBoid> allOtherFishes = CalamityMainMenu_Sunken.Fishes;
foreach (SunkenFishBoid other in allOtherFishes)
{
// Only school with other fishes that are nearby, of the same type and within the same depth.
bool isPrismaticGuppy = IsAPrismaticGuppy && other.IsAPrismaticGuppy;
bool schoolByFishType = isPrismaticGuppy || SelectedFishType == other.SelectedFishType;
float distance = Vector2.DistanceSquared(Position, other.Position);
if (distance < detetctionRadiusSquared && other != this && schoolByFishType && other.Depth == Depth)
{
float separationFactor = (separationDistanceSquared - distance) * Scale;
separation += (Position - other.Position) * separationFactor;
cohesion += other.Position;
alignment += other.Velocity;
totalSchoolMembers++;
}
}
if (totalSchoolMembers == 0)
return;
// Add all boids algorithm factors into the velocity.
cohesion /= totalSchoolMembers;
Velocity += (cohesion - Position).SafeNormalize(Vector2.Zero) * CohesionCoefficient;
alignment /= totalSchoolMembers;
Velocity += (alignment - Velocity).SafeNormalize(Vector2.Zero) * AlignmentCoefficient;
separation /= totalSchoolMembers;
Velocity += separation.SafeNormalize(Vector2.Zero) * SeparationCoefficient;
}
public void Draw(SpriteBatch spriteBatch)
{
if (!Initialized)
return;
Rectangle screenBounds = new Rectangle(-50, -50, Main.screenWidth + 100, Main.screenHeight + 100);
Vector2 depthFactor = new(1f / Depth, 1.1f / Depth);
Vector2 parallaxedPosition = Position * depthFactor;
// Don't draw anything if the fish is not within the screen bounds. No point in wasting resources on that.
if (!screenBounds.Contains((int)parallaxedPosition.X, (int)parallaxedPosition.Y))
return;
Texture2D fishTexture = GetCorrectFishTexture();
Rectangle frame = fishTexture.Frame(1, MaxFrames, 0, CurrentFrame);
Vector2 origin = frame.Size() * 0.5f;
float opacityByDepth = Utils.Remap(Depth, 1, 4, 0.8f, 0.6f, true) * Opacity;
float drawRotaton = Rotation + MathHelper.Pi;
float scaleByDepth = Scale / Depth;
SpriteEffects effects = (Velocity.X > 0f) ? SpriteEffects.FlipVertically : SpriteEffects.None;
spriteBatch.Draw(fishTexture, parallaxedPosition, frame, Color.White * opacityByDepth, drawRotaton, origin, scaleByDepth, effects, 0f);
}
private Texture2D GetCorrectFishTexture()
{
string sunkenSeaPath = "CalamityMod/NPCs/SunkenSea/";
Texture2D returnTexture = SelectedFishType switch
{
FishType.PolypPanasea => ModContent.Request<Texture2D>(sunkenSeaPath + PolypPanaseaTextureNames[FishTextureIndex]).Value,
FishType.PrismaticGuppy1 => ModContent.Request<Texture2D>(sunkenSeaPath + PrismaticGuppyTextureNames_1[FishTextureIndex]).Value,
FishType.PrismaticGuppy2 => ModContent.Request<Texture2D>(sunkenSeaPath + PrismaticGuppyTextureNames_2[FishTextureIndex]).Value,
FishType.PrismaticGuppy3 => ModContent.Request<Texture2D>(sunkenSeaPath + PrismaticGuppyTextureNames_3[FishTextureIndex]).Value,
_ => ModContent.Request<Texture2D>(sunkenSeaPath + SeaMinnowTextureNames[FishTextureIndex]).Value,
};
return returnTexture;
}
}
}