# Conflicts:
#	Graphics/Primitives/PrimitiveTrail.cs
#	NPCs/AcidRain/AcidEel.cs
#	NPCs/ExoMechs/Apollo/Apollo.cs
#	NPCs/ExoMechs/Ares/AresBody.cs
#	NPCs/ExoMechs/Artemis/Artemis.cs
#	NPCs/SupremeCalamitas/BrimstoneHeart.cs
#	Projectiles/Boss/ApolloChargeTelegraph.cs
#	Projectiles/Boss/AresTeslaOrb.cs
#	Projectiles/Boss/ArtemisChargeTelegraph.cs
#	Projectiles/Boss/ArtemisSpinLaserbeam.cs
#	Projectiles/Boss/CirrusPhotonRipperPrismTooth.cs
#	Projectiles/Boss/DraedonSummonLaser.cs
#	Projectiles/Boss/DyingSun.cs
#	Projectiles/DraedonsArsenal/PhaseslayerProjectile.cs
#	Projectiles/Enemy/GammRayBurst.cs
#	Projectiles/Magic/ApotheosisEnergy.cs
#	Projectiles/Magic/ArtAttackStar.cs
#	Projectiles/Magic/EternityHex.cs
#	Projectiles/Magic/FabBolt.cs
#	Projectiles/Magic/FabRay.cs
#	Projectiles/Magic/RainbowRocket.cs
#	Projectiles/Magic/WulfrumBolt.cs
#	Projectiles/Melee/Exobeam.cs
#	Projectiles/Melee/MarniteObliteratorProj.cs
#	Projectiles/Melee/PrismTooth.cs
#	Projectiles/Melee/RendingNeedle.cs
#	Projectiles/Melee/StygianShieldAttack.cs
#	Projectiles/Melee/TaintedBladeSlasher.cs
#	Projectiles/Melee/TerratomereBeam.cs
#	Projectiles/Melee/TerratomereBigSlash.cs
#	Projectiles/Melee/TerratomereHoldoutProj.cs
#	Projectiles/Melee/ViolenceSlashProjectile.cs
#	Projectiles/Melee/ViolenceThrownProjectile.cs
#	Projectiles/Ranged/ExoCrystalArrow.cs
#	Projectiles/Ranged/ExoLightningBolt.cs
#	Projectiles/Ranged/MeowCreature.cs
#	Projectiles/Ranged/PristineFire.cs
#	Projectiles/Ranged/SpeedBlasterShot.cs
#	Projectiles/Ranged/TelluricGlareArrow.cs
#	Projectiles/Ranged/TheMaelstromShark.cs
#	Projectiles/Rogue/DynamicPursuerElectricity.cs
#	Projectiles/Rogue/ScarletDevilProjectile.cs
#	Projectiles/Rogue/StormfrontLightning.cs
#	Projectiles/Rogue/WulfrumKnifeProj.cs
#	Projectiles/Summon/CosmilampBeam.cs
#	Projectiles/Summon/DaedalusLightning.cs
#	Projectiles/Summon/SmallAresArms/MinionTeslaOrb.cs
#	Projectiles/Summon/WulfrumDroid.cs
#	Projectiles/Summon/WulfrumEnergyBurst.cs
#	Projectiles/Summon/WulfrumFusionBolt.cs
#	Projectiles/Typeless/GemTechArmorGem.cs
#	Projectiles/Typeless/SuicideBomberDemon.cs
#	Projectiles/Typeless/WulfrumHook.cs
This commit is contained in:
tomat committed 2024-02-28 22:29:35 -08:00
commit c80265a899
73 files changed
+866 -759

No files matched your search

@@ -0,0 +1,20 @@
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives
{
/// <summary>
/// Use to sucessfully render primitives with pixelation with an NPC or Projectile.
/// </summary>
public interface IPixelatedPrimitiveRenderer
{
/// <summary>
/// The layer to render the primitive(s) to.
/// </summary>
PixelationPrimitiveLayer LayerToRenderTo => PixelationPrimitiveLayer.BeforeProjectiles;
/// <summary>
/// Render primitives that use pixelation here.
/// </summary>
void RenderPixelatedPrimitives(SpriteBatch spriteBatch);
}
}
@@ -0,0 +1,15 @@
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives
{
/// <summary>
/// Controls what layer the <see cref="IPixelatedPrimitiveRenderer.RenderPixelatedPrimitives"/> renders to.
/// </summary>
public enum PixelationPrimitiveLayer
{
BeforeNPCs,
AfterNPCs,
BeforeProjectiles,
AfterProjectiles
}
}
@@ -0,0 +1,158 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.ModLoader;
namespace CalamityMod.Graphics.Primitives
{
public class PrimitivePixelationSystem : ModSystem
{
#region Fields/Properties
private static ManagedRenderTarget PixelationTarget_BeforeNPCs;
private static ManagedRenderTarget PixelationTarget_AfterNPCs;
private static ManagedRenderTarget PixelationTarget_BeforeProjectiles;
private static ManagedRenderTarget PixelationTarget_AfterProjectiles;
private static RenderTarget2D CreatePixelTarget(int width, int height) => new(Main.instance.GraphicsDevice, width / 2, height / 2);
/// <summary>
/// Whether the system is currently rendering any primitives.
/// </summary>
public static bool CurrentlyRendering
{
get;
private set;
}
#endregion
#region Loading
public override void Load()
{
On_Main.CheckMonoliths += DrawToTargets;
On_Main.DoDraw_DrawNPCsOverTiles += DrawTarget_NPCs;
On_Main.DrawProjectiles += DrawTarget_Projectiles;
PixelationTarget_BeforeNPCs = new(true, CreatePixelTarget);
PixelationTarget_AfterNPCs = new(true, CreatePixelTarget);
PixelationTarget_BeforeProjectiles = new(true, CreatePixelTarget);
PixelationTarget_AfterProjectiles = new(true, CreatePixelTarget);
}
public override void Unload()
{
On_Main.CheckMonoliths -= DrawToTargets;
On_Main.DoDraw_DrawNPCsOverTiles -= DrawTarget_NPCs;
}
#endregion
#region Drawing To Targets
private void DrawToTargets(On_Main.orig_CheckMonoliths orig)
{
if (Main.gameMenu)
{
orig();
return;
}
var beforeNPCs = new List<IPixelatedPrimitiveRenderer>();
var afterNPCs = new List<IPixelatedPrimitiveRenderer>();
var beforeProjectiles = new List<IPixelatedPrimitiveRenderer>();
var afterProjectiles = new List<IPixelatedPrimitiveRenderer>();
// Check every active projectile.
for (int i = 0; i < Main.maxProjectiles; i++)
{
var projectile = Main.projectile[i];
// If the projectile is active, a mod projectile, and uses the interface, add it to the list of primitives to draw this frame.
if (projectile.active && projectile.ModProjectile != null && projectile.ModProjectile is IPixelatedPrimitiveRenderer pixelPrimitiveProjectile)
{
var listToUse = pixelPrimitiveProjectile.LayerToRenderTo switch
{
PixelationPrimitiveLayer.BeforeNPCs => beforeNPCs,
PixelationPrimitiveLayer.AfterNPCs => afterNPCs,
PixelationPrimitiveLayer.BeforeProjectiles => beforeProjectiles,
_ => afterProjectiles
};
listToUse.Add(pixelPrimitiveProjectile);
}
}
// Check every active NPC.
for (int i = 0; i < Main.maxNPCs; i++)
{
var npc = Main.npc[i];
// If the NPC is active, a mod NPC, and uses the interface, add it to the list of primitives to draw this frame.
if (npc.active && npc.ModNPC != null && npc.ModNPC is IPixelatedPrimitiveRenderer pixelPrimitiveNPC)
{
var listToUse = pixelPrimitiveNPC.LayerToRenderTo switch
{
PixelationPrimitiveLayer.BeforeNPCs => beforeNPCs,
PixelationPrimitiveLayer.AfterNPCs => afterNPCs,
PixelationPrimitiveLayer.BeforeProjectiles => beforeProjectiles,
_ => afterProjectiles
};
listToUse.Add(pixelPrimitiveNPC);
}
}
CurrentlyRendering = true;
DrawPrimsToRenderTarget(PixelationTarget_BeforeNPCs, beforeNPCs);
DrawPrimsToRenderTarget(PixelationTarget_AfterNPCs, afterNPCs);
DrawPrimsToRenderTarget(PixelationTarget_BeforeProjectiles, beforeProjectiles);
DrawPrimsToRenderTarget(PixelationTarget_AfterProjectiles, afterProjectiles);
Main.instance.GraphicsDevice.SetRenderTarget(null);
CurrentlyRendering = false;
orig();
}
private static void DrawPrimsToRenderTarget(RenderTarget2D renderTarget, List<IPixelatedPrimitiveRenderer> pixelPrimitives)
{
// Swap to the target regardless, in order to clear any leftover content from last frame. Not doing this results in the final frame lingering once it stops rendering.
renderTarget.SwapTo();
if (pixelPrimitives.Any())
{
Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null);
foreach (var pixelPrimitiveDrawer in pixelPrimitives)
pixelPrimitiveDrawer.RenderPixelatedPrimitives(Main.spriteBatch);
Main.spriteBatch.End();
}
}
#endregion
#region Target Drawing
private void DrawTarget_NPCs(On_Main.orig_DoDraw_DrawNPCsOverTiles orig, Main self)
{
DrawTargetScaled(PixelationTarget_BeforeNPCs);
orig(self);
DrawTargetScaled(PixelationTarget_AfterNPCs);
}
private void DrawTarget_Projectiles(On_Main.orig_DrawProjectiles orig, Main self)
{
DrawTargetScaled(PixelationTarget_BeforeProjectiles);
orig(self);
DrawTargetScaled(PixelationTarget_AfterProjectiles);
}
private static void DrawTargetScaled(ManagedRenderTarget target)
{
Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, Main.Rasterizer, null, Main.GameViewMatrix.TransformationMatrix);
Main.spriteBatch.Draw(target, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, 2f, SpriteEffects.None, 0f);
Main.spriteBatch.End();
}
#endregion
}
}
+296
View File
@@ -0,0 +1,296 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Graphics.Shaders;
namespace CalamityMod.Graphics.Primitives
{
/// <summary>
/// This both acts as an instanceable struct containing primitive trail data, and as a manager that creates and renders said instances. <br/><br/>
/// <b>To use normally, in the draw method of an NPC or Projectile call <see cref="Prepare"/>.</b><br/>
/// <list type="bullet">
/// <item>The first param should be the positions to use for the trail.</item>
/// <item>The second is a struct that allows you to choose a desired configuration of settings to use with the trail, to allow for customization.</item>
/// <item>The third controls how many points are created for the trail, and the fourth determines whether the primitive is subsequently rendered.</item>
/// <item>If you do not render in <see cref="Prepare"/>, you <b>MUST</b> call <see cref="Render"/> manually on the created instance to make it actually appear.</item>
/// </list>
/// If you wish to use pixelation, you <b>MUST</b> make the NPC/Projectile inherit <see cref="IPixelatedPrimitiveRenderer"/> and use <see cref="IPixelatedPrimitiveRenderer.RenderPixelatedPrimitives"/> instead.<br/>
/// You can also optionally specify a render layer with <see cref="IPixelatedPrimitiveRenderer.LayerToRenderTo"/>. It is <see cref="PixelationPrimitiveLayer.BeforeNPCs"/> by default.
/// </summary>
public readonly struct PrimitiveSet
{
#region Instance Members
/// <summary>
/// The vertices of the set.
/// </summary>
public readonly VertexPosition2DColorTexture[] Vertices;
/// <summary>
/// The indices of the set.
/// </summary>
public readonly int[] Indices;
/// <summary>
/// The settings of the set.
/// </summary>
public readonly PrimitiveSettings Settings;
private PrimitiveSet(VertexPosition2DColorTexture[] vertices, int[] indices, PrimitiveSettings settings)
{
Vertices = vertices;
Indices = indices;
Settings = settings;
}
#endregion
#region Static Members
private static void PerformPixelationSafetyChecks(PrimitiveSettings settings)
{
// Don't allow accidental screw ups with these.
if (settings.Pixelate && !PrimitivePixelationSystem.CurrentlyRendering)
throw new Exception("Error: Primitives using pixelation MUST be prepared/rendered from the IPixelatedPrimitiveRenderer.RenderPixelatedPrimitives method, did you forget to use the interface?");
else if (!settings.Pixelate && PrimitivePixelationSystem.CurrentlyRendering)
throw new Exception("Error: Primitives not using pixelation MUST NOT be prepared/rendered from the IPixelatedPrimitiveRenderer.RenderPixelatedPrimitives method.");
}
/// <summary>
/// Prepares a <see cref="PrimitiveSet"/> based on the provided information, and optionally renders it.
/// </summary>
/// <param name="positions">The list of positions to use. Keep in mind that these are expected to be in <b>world position</b>, and <see cref="Main.screenPosition"/> is automatically subtracted from them all.</param>
/// <param name="settings">The primitive draw settings to use.</param>
/// <param name="pointsToCreate">The amount of points to use. More is higher detailed, but less performant. By default, is the number of positions provided. <b>Going above 100 is NOT recommended.</b></param>
/// <param name="render">Whether to render the set.</param>
/// <returns>The prepared set.</returns>
public static PrimitiveSet? Prepare(IEnumerable<Vector2> positions, PrimitiveSettings settings, int? pointsToCreate = null, bool render = true)
{
PerformPixelationSafetyChecks(settings);
int positionCount = positions.Count();
// Return if not enough to draw anything.
if (positionCount <= 2)
return null;
// Cull out any zeroed points.
positions = positions.Where(p => p != Vector2.Zero);
List<Vector2> trailPoints = PreparePointsRectangleTrail(positions, settings, pointsToCreate ?? positionCount).ToList();
// A trail with only one point or less has nothing to connect to, and therefore, can't make a trail.
if (trailPoints.Count <= 2)
return null;
// If the trail point has any NaN positions, don't draw anything.
if (trailPoints.Any(point => point.HasNaNs()))
return null;
// If the trail points are all equal, don't draw anything.
if (trailPoints.All(point => point == trailPoints[0]))
return null;
IEnumerable<VertexPosition2DColorTexture> vertices = CreateVerticesRectangleTrail(trailPoints.ToList(), settings);
int[] indices = CreateIndicesRectangleTrail(trailPoints.Count);
// Create the set, and just return it if not asked to render.
PrimitiveSet set = new(vertices.ToArray(), indices, settings);
if (!render)
return set;
// Else render the set and return it.
return set.Render();
}
#endregion
#region Instance Methods
/// <summary>
/// Renders the provided primitive set to the screen.
/// </summary>
/// <returns>The provided set.</returns>
public PrimitiveSet Render()
{
PerformPixelationSafetyChecks(Settings);
if (Indices.Length % 6 != 0 || Vertices.Length <= 3)
return this;
// Perform screen culling, for performance reasons.
Main.instance.GraphicsDevice.RasterizerState = RasterizerState.CullNone;
Main.instance.GraphicsDevice.RasterizerState.ScissorTestEnable = true;
Main.instance.GraphicsDevice.ScissorRectangle = new Rectangle(0, 0, Main.screenWidth, Main.screenHeight);
Matrix view;
Matrix projection;
if (Settings.Pixelate)
CalcuatePixelatedPerspectiveMatrices(out view, out projection);
else
CalamityUtils.CalculatePerspectiveMatricies(out view, out projection);
var shaderToUse = Settings.Shader ?? GameShaders.Misc["CalamityMod:StandardPrimitiveShader"];
shaderToUse.Shader.Parameters["uWorldViewProjection"].SetValue(view * projection);
shaderToUse.Apply();
// Render the set.
Main.instance.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, Vertices, 0, Vertices.Length, Indices, 0, Indices.Length / 3);
Main.pixelShader.CurrentTechnique.Passes[0].Apply();
return this;
}
#endregion
#region Set Preperation
private static IEnumerable<Vector2> PreparePointsRectangleTrail(IEnumerable<Vector2> positions, PrimitiveSettings settings, int pointsToCreate)
{
// Don't smoothen the points unless explicitly told do so.
if (!settings.Smoothen)
{
List<Vector2> basePoints = positions.Where(originalPosition => originalPosition != Vector2.Zero).ToList();
List<Vector2> endPoints = new();
if (basePoints.Count <= 2)
return endPoints;
// Remap the original positions across a certain length.
for (int i = 0; i < pointsToCreate; i++)
{
float completionRatio = i / (float)(pointsToCreate - 1f);
int currentIndex = (int)(completionRatio * (basePoints.Count - 1));
Vector2 currentPoint = basePoints[currentIndex];
Vector2 nextPoint = basePoints[(currentIndex + 1) % basePoints.Count];
endPoints.Add(Vector2.Lerp(currentPoint, nextPoint, completionRatio * (basePoints.Count - 1) % 0.99999f) - Main.screenPosition);
}
return endPoints;
}
List<Vector2> controlPoints = new();
for (int i = 0; i < positions.Count(); i++)
{
// Don't incorporate points that are zeroed out.
// They are almost certainly a result of incomplete oldPos arrays.
if (positions.ElementAt(i) == Vector2.Zero)
continue;
float completionRatio = i / (float)positions.Count();
Vector2 offset = -Main.screenPosition;
if (settings.OffsetFunction != null)
offset += settings.OffsetFunction(completionRatio);
controlPoints.Add(positions.ElementAt(i) + offset);
}
List<Vector2> points = new();
// Avoid stupid index errors.
if (controlPoints.Count <= 4)
return controlPoints;
for (int j = 0; j < pointsToCreate; j++)
{
float splineInterpolant = j / (float)pointsToCreate;
float localSplineInterpolant = splineInterpolant * (controlPoints.Count - 1f) % 1f;
int localSplineIndex = (int)(splineInterpolant * (controlPoints.Count - 1f));
Vector2 farLeft;
Vector2 left = controlPoints[localSplineIndex];
Vector2 right = controlPoints[localSplineIndex + 1];
Vector2 farRight;
// Special case: If the spline attempts to access the previous/next index but the index is already at the very beginning/end, simply
// cheat a little bit by creating a phantom point that's mirrored from the previous one.
if (localSplineIndex <= 0)
{
Vector2 mirrored = left * 2f - right;
farLeft = mirrored;
}
else
farLeft = controlPoints[localSplineIndex - 1];
if (localSplineIndex >= controlPoints.Count - 2)
{
Vector2 mirrored = right * 2f - left;
farRight = mirrored;
}
else
farRight = controlPoints[localSplineIndex + 2];
points.Add(Vector2.CatmullRom(farLeft, left, right, farRight, localSplineInterpolant));
}
// Manually insert the front and end points.
points.Insert(0, controlPoints.First());
points.Add(controlPoints.Last());
return points;
}
private static IEnumerable<VertexPosition2DColorTexture> CreateVerticesRectangleTrail(List<Vector2> positions, PrimitiveSettings settings)
{
List<VertexPosition2DColorTexture> vertices = new();
for (int i = 0; i < positions.Count; i++)
{
float completionRatio = i / (float)(positions.Count - 1);
float widthAtVertex = settings.WidthFunction(completionRatio);
Color vertexColor = settings.ColorFunction(completionRatio);
Vector2 currentPosition = positions[i];
Vector2 directionToAhead = i == positions.Count - 1 ? (positions[i] - positions[i - 1]).SafeNormalize(Vector2.Zero) : (positions[i + 1] - positions[i]).SafeNormalize(Vector2.Zero);
Vector2 leftCurrentTextureCoord = new(completionRatio, 0f);
Vector2 rightCurrentTextureCoord = new(completionRatio, 1f);
// Point 90 degrees away from the direction towards the next point, and use it to mark the edges of the rectangle.
// This doesn't use RotatedBy for the sake of performance (there can potentially be a lot of trail points).
Vector2 sideDirection = new(-directionToAhead.Y, directionToAhead.X);
Vector2 left = currentPosition - sideDirection * widthAtVertex;
Vector2 right = currentPosition + sideDirection * widthAtVertex;
// Override the initial vertex positions if requested.
if (i == 0 && settings.InitialVertexPositionsOverride.HasValue && settings.InitialVertexPositionsOverride.Value.Item1 != Vector2.Zero && settings.InitialVertexPositionsOverride.Value.Item2 != Vector2.Zero)
{
left = settings.InitialVertexPositionsOverride.Value.Item1;
right = settings.InitialVertexPositionsOverride.Value.Item2;
}
// What this is doing, at its core, is defining a rectangle based on two triangles.
// These triangles are defined based on the width of the strip at that point.
// The resulting rectangles combined are what make the trail itself.
vertices.Add(new VertexPosition2DColorTexture(left, vertexColor, leftCurrentTextureCoord));
vertices.Add(new VertexPosition2DColorTexture(right, vertexColor, rightCurrentTextureCoord));
}
return vertices;
}
private static int[] CreateIndicesRectangleTrail(int pointCount)
{
// What this is doing is basically representing each point on the vertices list as
// indices. These indices should come together to create a tiny rectangle that acts
// as a segment on the trail. This is achieved here by splitting the indices (or rather, points)
// into 2 triangles, which requires 6 points.
// The logic here basically determines which indices are connected together.
int totalIndices = (pointCount - 1) * 6;
int[] indices = new int[totalIndices];
for (int i = 0; i < pointCount - 2; i++)
{
int startingTriangleIndex = i * 6;
int connectToIndex = i * 2;
indices[startingTriangleIndex] = connectToIndex;
indices[startingTriangleIndex + 1] = connectToIndex + 1;
indices[startingTriangleIndex + 2] = connectToIndex + 2;
indices[startingTriangleIndex + 3] = connectToIndex + 2;
indices[startingTriangleIndex + 4] = connectToIndex + 1;
indices[startingTriangleIndex + 5] = connectToIndex + 3;
}
return indices;
}
private static void CalcuatePixelatedPerspectiveMatrices(out Matrix viewMatrix, out Matrix projectionMatrix)
{
// Due to the scaling, the normal transformation calcuations do not work with pixelated primitives.
projectionMatrix = Matrix.CreateOrthographicOffCenter(0, Main.screenWidth, Main.screenHeight, 0, -1, 1);
viewMatrix = Matrix.Identity;
}
#endregion
}
}
+92
View File
@@ -0,0 +1,92 @@
using Microsoft.Xna.Framework;
using Terraria.Graphics.Shaders;
namespace CalamityMod.Graphics.Primitives
{
/// <summary>
/// Contains all the various options to use when creating a primitive trail. New members can be added freely without breaking existing implementations.
/// </summary>
public readonly struct PrimitiveSettings
{
#region Delegates
/// <summary>
/// A delegate to dynamically determine the width of the trail at each position.
/// </summary>
/// <param name="trailLengthInterpolant">The current position along the trail as a 0-1 interlopant value.</param>
/// <returns>The width for the current point.</returns>
public delegate float VertexWidthFunction(float trailLengthInterpolant);
/// <summary>
/// A delegate to dynamically determine the color of the trail at each position.
/// </summary>
/// <param name="trailLengthInterpolant">The current position along the trail as a 0-1 interlopant value.</param>
/// <returns>The color for the current point.</returns>
public delegate Color VertexColorFunction(float trailLengthInterpolant);
/// <summary>
/// A delegate to dynamically determine the offset of the trail at each position.
/// </summary>
/// <param name="trailLengthInterpolant">The current position along the trail as a 0-1 interlopant value.</param>
/// <returns>The offset for the current point.</returns>
public delegate Vector2 VertexOffsetFunction(float trailLengthInterpolant);
#endregion
#region Instance Fields
/// <summary>
/// Used to determine the width of each vertex.
/// </summary>
public readonly VertexWidthFunction WidthFunction;
/// <summary>
/// Used to determine the color of each vertex.
/// </summary>
public readonly VertexColorFunction ColorFunction;
/// <summary>
/// Used to offset each position when generating them.
/// </summary>
public readonly VertexOffsetFunction OffsetFunction;
/// <summary>
/// Whether to use smoothening when generating the vertex positions from the provided ones Recommended to be on by default.
/// </summary>
public readonly bool Smoothen;
/// <summary>
/// Whether to pixelate the primitives. Recommended to be on by default.
/// </summary>
public readonly bool Pixelate;
/// <summary>
/// The shader to apply when rendering.
/// </summary>
public readonly MiscShaderData Shader;
/// <summary>
/// An optional override to force the trail to use the provided positions as the side positions of the initial vertex. They are the left and right positions respectively.
/// </summary>
public readonly (Vector2, Vector2)? InitialVertexPositionsOverride;
#endregion
/// <summary>
/// Contains all the various options to use when creating a primitive trail.
/// </summary>
/// <param name="widthFunction">Used to determine the width of each vertex.</param>
/// <param name="colorFunction">Used to determine the color of each vertex.</param>
/// <param name="offsetFunction">Used to offset each position when generating them.</param>
/// <param name="smoothen">Whether to use smoothening when generating the vertex positions from the provided ones. Recommended to be enabled.</param>
/// <param name="pixelate">Whether to pixelate the primitives. Recommended to be enabled if the effect was designed with this in mind.</param>
/// <param name="shader">The shader to apply when rendering the primitives.</param>
/// <param name="initialVertexPositionsOverride">An optional override to force the trail to use the provided positions as the side positions of the initial vertex. They are the left and right positions respectively and should be in screen space.</param>
public PrimitiveSettings(VertexWidthFunction widthFunction, VertexColorFunction colorFunction, VertexOffsetFunction offsetFunction = null, bool smoothen = true, bool pixelate = false, MiscShaderData shader = null, (Vector2, Vector2)? initialVertexPositionsOverride = null)
{
WidthFunction = widthFunction;
ColorFunction = colorFunction;
OffsetFunction = offsetFunction;
Smoothen = smoothen;
Pixelate = pixelate;
Shader = shader;
InitialVertexPositionsOverride = initialVertexPositionsOverride;
}
}
}
-262
View File
@@ -1,262 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using CalamityMod.DataStructures;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Graphics.Shaders;
namespace CalamityMod
{
public class PrimitiveTrail
{
public struct VertexPosition2DColor : IVertexType
{
public Vector2 Position;
public Color Color;
public Vector2 TextureCoordinates;
public VertexDeclaration VertexDeclaration => _vertexDeclaration;
private static readonly VertexDeclaration _vertexDeclaration = new VertexDeclaration(new VertexElement[]
{
new VertexElement(0, VertexElementFormat.Vector2, VertexElementUsage.Position, 0),
new VertexElement(8, VertexElementFormat.Color, VertexElementUsage.Color, 0),
new VertexElement(12, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0),
});
public VertexPosition2DColor(Vector2 position, Color color, Vector2 textureCoordinates)
{
Position = position;
Color = color;
TextureCoordinates = textureCoordinates;
}
}
public delegate float VertexWidthFunction(float completionRatio);
public delegate Color VertexColorFunction(float completionRatio);
public int DegreeOfBezierCurveCornerSmoothening;
public VertexWidthFunction WidthFunction;
public VertexColorFunction ColorFunction;
public MiscShaderData SpecialShader;
public TrailPointRetrievalFunction TrailPointFunction;
public Vector2 OverridingStickPointStart = Vector2.Zero;
public Vector2 OverridingStickPointEnd = Vector2.Zero;
public delegate List<Vector2> TrailPointRetrievalFunction(IEnumerable<Vector2> originalPositions, Vector2 generalOffset, int totalTrailPoints, IEnumerable<float> originalRotations = null);
public PrimitiveTrail(VertexWidthFunction widthFunction, VertexColorFunction colorFunction, TrailPointRetrievalFunction pointFunction = null, MiscShaderData specialShader = null)
{
if (widthFunction is null || colorFunction is null)
throw new NullReferenceException($"In order to create a primitive trail, a non-null {(widthFunction is null ? "width" : "color")} function must be specified.");
WidthFunction = widthFunction;
ColorFunction = colorFunction;
// Default to bezier smoothening if nothing else is inputted.
if (pointFunction is null)
pointFunction = SmoothBezierPointRetreivalFunction;
TrailPointFunction = pointFunction;
SpecialShader = specialShader ?? GameShaders.Misc["CalamityMod:StandardPrimitiveShader"];
if (specialShader != null)
SpecialShader = specialShader;
}
public static List<Vector2> RigidPointRetreivalFunction(IEnumerable<Vector2> originalPositions, Vector2 generalOffset, int totalTrailPoints, IEnumerable<float> _ = null)
{
List<Vector2> basePoints = originalPositions.Where(originalPosition => originalPosition != Vector2.Zero).ToList();
List<Vector2> endPoints = new List<Vector2>();
if (basePoints.Count < 2)
{
for (int i = 0; i < basePoints.Count; i++)
basePoints[i] += generalOffset;
return basePoints;
}
// Remap the original positions across a certain length.
for (int i = 0; i < totalTrailPoints; i++)
{
float completionRatio = i / (float)(totalTrailPoints - 1f);
int currentIndex = (int)(completionRatio * (basePoints.Count - 1));
Vector2 currentPoint = basePoints[currentIndex];
Vector2 nextPoint = basePoints[(currentIndex + 1) % basePoints.Count];
endPoints.Add(Vector2.Lerp(currentPoint, nextPoint, completionRatio * (basePoints.Count - 1) % 0.99999f) + generalOffset);
}
endPoints.Add(basePoints.Last() + generalOffset);
return endPoints;
}
// NOTE: Beziers can be laggy when a lot of control points are used, since our implementation
// uses a recursive Lerp that gets more computationally expensive the more original indices.
// n(n + 1)/2 linear interpolations to be precise, where n is the amount of original indices.
public List<Vector2> SmoothBezierPointRetreivalFunction(IEnumerable<Vector2> originalPositions, Vector2 generalOffset, int totalTrailPoints, IEnumerable<float> originalRotations = null)
{
List<Vector2> controlPoints = new List<Vector2>();
for (int i = 0; i < originalPositions.Count(); i++)
{
// Don't incorporate points that are zeroed out.
// They are almost certainly a result of incomplete oldPos arrays.
if (originalPositions.ElementAt(i) == Vector2.Zero)
continue;
controlPoints.Add(originalPositions.ElementAt(i) + generalOffset);
}
bool pointCountCondition = DegreeOfBezierCurveCornerSmoothening <= 0 || controlPoints.Count < DegreeOfBezierCurveCornerSmoothening * 3;
int effectivePointCount = DegreeOfBezierCurveCornerSmoothening > 0 ? totalTrailPoints * DegreeOfBezierCurveCornerSmoothening : totalTrailPoints;
BezierCurve bezierCurve = new BezierCurve(controlPoints.Where((_, i) =>
{
return DegreeOfBezierCurveCornerSmoothening <= 0 ||
i % DegreeOfBezierCurveCornerSmoothening == 0 ||
i == 0 ||
i == controlPoints.Count - 1 ||
pointCountCondition;
}).ToArray());
return controlPoints.Count <= 1 ? controlPoints : bezierCurve.GetPoints(effectivePointCount);
}
// Using this method requires oldRot be supplied to the Draw method for the sake of determining how many points need to be made at a given time step.
// Furthermore, since the point count is dynamic, the point count int parameter has no purpose. It can be supplied simply with zero.
public static List<Vector2> SmoothCatmullRomPointRetreivalFunction(IEnumerable<Vector2> originalPositions, Vector2 generalOffset, int _, IEnumerable<float> originalRotations)
{
List<Vector2> smoothenedPoints = new List<Vector2>();
for (int i = 0; i < originalPositions.Count() - 1; i++)
{
Vector2 currentPosition = originalPositions.ElementAt(i);
Vector2 aheadPosition = originalPositions.ElementAt(i + 1);
// Don't incorporate points that are zeroed out.
// They are almost certainly a result of incomplete oldPos arrays.
if (currentPosition == Vector2.Zero || aheadPosition == Vector2.Zero)
continue;
float currentRotation = MathHelper.WrapAngle(originalRotations.ElementAt(i));
float aheadRotation = MathHelper.WrapAngle(originalRotations.ElementAt(i + 1));
// Determine the amount of extra points to draw based on the rotational offset between the two time steps.
int pointsToAdd = (int)Math.Round(Math.Abs(MathHelper.WrapAngle(aheadRotation - currentRotation)) * 8f / MathHelper.Pi);
// Add a base point.
smoothenedPoints.Add(currentPosition + generalOffset);
// If no new points are needed, skip this.
if (pointsToAdd == 0)
continue;
float segmentLength = Vector2.Distance(currentPosition, aheadPosition);
float increment = 1f / (pointsToAdd + 2);
Vector2 backEnd = currentPosition + currentRotation.ToRotationVector2() * segmentLength;
Vector2 frontEnd = aheadPosition + aheadRotation.ToRotationVector2() * -segmentLength;
// Create smoothened points based on a Catmull-Rom spline.
for (float j = increment; j < 1f; j += increment)
smoothenedPoints.Add(Vector2.CatmullRom(backEnd, currentPosition, aheadPosition, frontEnd, j) + generalOffset);
}
return smoothenedPoints;
}
public VertexPosition2DColor[] GetVerticesFromTrailPoints(List<Vector2> trailPoints)
{
VertexPosition2DColor[] vertices = new VertexPosition2DColor[trailPoints.Count * 2 - 2];
for (int i = 0; i < trailPoints.Count - 1; i++)
{
float completionRatio = i / (float)trailPoints.Count;
float widthAtVertex = WidthFunction(completionRatio);
Color vertexColor = ColorFunction(completionRatio);
Vector2 currentPosition = trailPoints[i];
Vector2 positionAhead = trailPoints[i + 1];
Vector2 directionToAhead = (positionAhead - trailPoints[i]).SafeNormalize(Vector2.Zero);
Vector2 leftCurrentTextureCoord = new Vector2(completionRatio, 0f);
Vector2 rightCurrentTextureCoord = new Vector2(completionRatio, 1f);
// Point 90 degrees away from the direction towards the next point, and use it to mark the edges of the rectangle.
// This doesn't use RotatedBy for the sake of performance (there can potentially be a lot of trail points).
Vector2 sideDirection = new Vector2(-directionToAhead.Y, directionToAhead.X);
Vector2 left = currentPosition - sideDirection * widthAtVertex;
Vector2 right = currentPosition + sideDirection * widthAtVertex;
if (i == 0 && OverridingStickPointStart != Vector2.Zero)
{
left = OverridingStickPointStart;
right = OverridingStickPointEnd;
}
// What this is doing, at its core, is defining a rectangle based on two triangles.
// These triangles are defined based on the width of the strip at that point.
// The resulting rectangles combined are what make the trail itself.
vertices[i * 2] = new VertexPosition2DColor(left, vertexColor, leftCurrentTextureCoord);
vertices[i * 2 + 1] = new VertexPosition2DColor(right, vertexColor, rightCurrentTextureCoord);
}
return vertices.ToArray();
}
public short[] GetIndicesFromTrailPoints(int pointCount)
{
// What this is doing is basically representing each point on the vertices list as
// indices. These indices should come together to create a tiny rectangle that acts
// as a segment on the trail. This is achieved here by splitting the indices (or rather, points)
// into 2 triangles, which requires 6 points.
// The logic here basically determines which indices are connected together.
int totalIndices = (pointCount - 1) * 6;
short[] indices = new short[totalIndices];
for (int i = 0; i < pointCount - 2; i++)
{
int startingTriangleIndex = i * 6;
int connectToIndex = i * 2;
indices[startingTriangleIndex] = (short)connectToIndex;
indices[startingTriangleIndex + 1] = (short)(connectToIndex + 1);
indices[startingTriangleIndex + 2] = (short)(connectToIndex + 2);
indices[startingTriangleIndex + 3] = (short)(connectToIndex + 2);
indices[startingTriangleIndex + 4] = (short)(connectToIndex + 1);
indices[startingTriangleIndex + 5] = (short)(connectToIndex + 3);
}
return indices;
}
public void Draw(IEnumerable<Vector2> originalPositions, Vector2 generalOffset, int totalTrailPoints, IEnumerable<float> originalRotations = null)
{
List<Vector2> trailPoints = TrailPointFunction(originalPositions, generalOffset, totalTrailPoints, originalRotations);
// A trail with only one point or less has nothing to connect to, and therefore, can't make a trail.
if (trailPoints.Count < 2)
return;
// If the trail points have any NaN positions, don't draw anything.
if (trailPoints.Any(point => point.HasNaNs()))
return;
// If the trail points are all equal, don't draw anything.
if (trailPoints.All(point => point == trailPoints[0]))
return;
CalamityUtils.CalculatePerspectiveMatricies(out Matrix view, out Matrix projection);
VertexPosition2DColor[] vertices = GetVerticesFromTrailPoints(trailPoints);
short[] triangleIndices = GetIndicesFromTrailPoints(trailPoints.Count);
// Don't draw anything if the indicies/vertices are in any way invalid.
// If they are, the graphics engine, along with the entire game, will crash.
if (triangleIndices.Length % 6 != 0 || vertices.Length % 2 != 0)
return;
Main.instance.GraphicsDevice.RasterizerState = RasterizerState.CullNone;
Main.instance.GraphicsDevice.RasterizerState.ScissorTestEnable = true;
Main.instance.GraphicsDevice.ScissorRectangle = new Rectangle(0, 0, Main.screenWidth, Main.screenHeight); //offscreen culling
SpecialShader.Shader.Parameters["uWorldViewProjection"].SetValue(view * projection);
SpecialShader.Apply();
Main.instance.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, vertices.Length, triangleIndices, 0, triangleIndices.Length / 3);
Main.pixelShader.CurrentTechnique.Passes[0].Apply();
}
}
}
@@ -0,0 +1,46 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives
{
/// <summary>
/// A custom vertex type with a position using Vector2 instead of Vector4, as Terraria is only a 2D game.
/// </summary>
/// <remarks>This represents a vertex that will be rendered by the GPU.</remarks>
public readonly struct VertexPosition2DColorTexture : IVertexType
{
/// <summary>
/// The position of the vertex.
/// </summary>
public readonly Vector2 Position;
/// <summary>
/// The color of the vertex.
/// </summary>
public readonly Color Color;
/// <summary>
/// The texture-coordinate of the vertex.
/// </summary>
public readonly Vector2 TextureCoordinates;
/// <summary>
/// The vertex declaration. This declares the layout and size of the data in the vertex shader.
/// </summary>
public VertexDeclaration VertexDeclaration => VertexDeclaration2D;
public static readonly VertexDeclaration VertexDeclaration2D = new(new VertexElement[]
{
new(0, VertexElementFormat.Vector2, VertexElementUsage.Position, 0),
new(8, VertexElementFormat.Color, VertexElementUsage.Color, 0),
new(12, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0),
});
public VertexPosition2DColorTexture(Vector2 position, Color color, Vector2 textureCoordinates)
{
Position = position;
Color = color;
TextureCoordinates = textureCoordinates;
}
}
}