// Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Utils; using osuTK; using osuTK.Graphics; using System; using osu.Framework.Graphics.Shaders; using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Primitives; using osu.Framework.Allocation; using System.Collections.Generic; using osu.Framework.Graphics.Batches; using osu.Framework.Graphics.OpenGL.Vertices; using osu.Framework.Lists; namespace osu.Game.Graphics.Backgrounds { public class Triangles : Drawable { private const float triangle_size = 100; private const float base_velocity = 50; /// /// How many screen-space pixels are smoothed over. /// Same behavior as Sprite's EdgeSmoothness. /// private const float edge_smoothness = 1; private Color4 colourLight = Color4.White; public Color4 ColourLight { get => colourLight; set { if (colourLight == value) return; colourLight = value; updateColours(); } } private Color4 colourDark = Color4.Black; public Color4 ColourDark { get => colourDark; set { if (colourDark == value) return; colourDark = value; updateColours(); } } /// /// Whether we want to expire triangles as they exit our draw area completely. /// [Obsolete("Unused.")] // Can be removed 20210518 protected virtual bool ExpireOffScreenTriangles => true; /// /// Whether we should create new triangles as others expire. /// protected virtual bool CreateNewTriangles => true; /// /// The amount of triangles we want compared to the default distribution. /// protected virtual float SpawnRatio => 1; private float triangleScale = 1; /// /// Whether we should drop-off alpha values of triangles more quickly to improve /// the visual appearance of fading. This defaults to on as it is generally more /// aesthetically pleasing, but should be turned off in buffered containers. /// public bool HideAlphaDiscrepancies = true; /// /// The relative velocity of the triangles. Default is 1. /// public float Velocity = 1; private readonly SortedList parts = new SortedList(Comparer.Default); private Random stableRandom; private IShader shader; private readonly Texture texture; /// /// Construct a new triangle visualisation. /// /// An optional seed to stabilise random positions / attributes. Note that this does not guarantee stable playback when seeking in time. public Triangles(int? seed = null) { if (seed != null) stableRandom = new Random(seed.Value); texture = Texture.WhitePixel; } [BackgroundDependencyLoader] private void load(ShaderManager shaders) { shader = shaders.Load(VertexShaderDescriptor.TEXTURE_2, FragmentShaderDescriptor.TEXTURE_ROUNDED); } protected override void LoadComplete() { base.LoadComplete(); addTriangles(true); } public float TriangleScale { get => triangleScale; set { float change = value / triangleScale; triangleScale = value; for (int i = 0; i < parts.Count; i++) { TriangleParticle newParticle = parts[i]; newParticle.Scale *= change; parts[i] = newParticle; } } } protected override void Update() { base.Update(); Invalidate(Invalidation.DrawNode); if (CreateNewTriangles) addTriangles(false); float adjustedAlpha = HideAlphaDiscrepancies // Cubically scale alpha to make it drop off more sharply. ? MathF.Pow(DrawColourInfo.Colour.AverageColour.Linear.A, 3) : 1; float elapsedSeconds = (float)Time.Elapsed / 1000; // Since position is relative, the velocity needs to scale inversely with DrawHeight. // Since we will later multiply by the scale of individual triangles we normalize by // dividing by triangleScale. float movedDistance = -elapsedSeconds * Velocity * base_velocity / (DrawHeight * triangleScale); for (int i = 0; i < parts.Count; i++) { TriangleParticle newParticle = parts[i]; // Scale moved distance by the size of the triangle. Smaller triangles should move more slowly. newParticle.Position.Y += parts[i].Scale * movedDistance; newParticle.Colour.A = adjustedAlpha; parts[i] = newParticle; float bottomPos = parts[i].Position.Y + triangle_size * parts[i].Scale * 0.866f / DrawHeight; if (bottomPos < 0) parts.RemoveAt(i); } } /// /// Clears and re-initialises triangles according to a given seed. /// /// An optional seed to stabilise random positions / attributes. Note that this does not guarantee stable playback when seeking in time. public void Reset(int? seed = null) { if (seed != null) stableRandom = new Random(seed.Value); parts.Clear(); addTriangles(true); } protected int AimCount { get; private set; } private void addTriangles(bool randomY) { AimCount = (int)(DrawWidth * DrawHeight * 0.002f / (triangleScale * triangleScale) * SpawnRatio); for (int i = 0; i < AimCount - parts.Count; i++) parts.Add(createTriangle(randomY)); } private TriangleParticle createTriangle(bool randomY) { TriangleParticle particle = CreateTriangle(); particle.Position = new Vector2(nextRandom(), randomY ? nextRandom() : 1); particle.ColourShade = nextRandom(); particle.Colour = CreateTriangleShade(particle.ColourShade); return particle; } /// /// Creates a triangle particle with a random scale. /// /// The triangle particle. protected virtual TriangleParticle CreateTriangle() { const float std_dev = 0.16f; const float mean = 0.5f; float u1 = 1 - nextRandom(); //uniform(0,1] random floats float u2 = 1 - nextRandom(); float randStdNormal = (float)(Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2)); // random normal(0,1) var scale = Math.Max(triangleScale * (mean + std_dev * randStdNormal), 0.1f); // random normal(mean,stdDev^2) return new TriangleParticle { Scale = scale }; } /// /// Creates a shade of colour for the triangles. /// /// The colour. protected virtual Color4 CreateTriangleShade(float shade) => Interpolation.ValueAt(shade, colourDark, colourLight, 0, 1); private void updateColours() { for (int i = 0; i < parts.Count; i++) { TriangleParticle newParticle = parts[i]; newParticle.Colour = CreateTriangleShade(newParticle.ColourShade); parts[i] = newParticle; } } private float nextRandom() => (float)(stableRandom?.NextDouble() ?? RNG.NextSingle()); protected override DrawNode CreateDrawNode() => new TrianglesDrawNode(this); private class TrianglesDrawNode : DrawNode { protected new Triangles Source => (Triangles)base.Source; private IShader shader; private Texture texture; private readonly List parts = new List(); private Vector2 size; private QuadBatch vertexBatch; public TrianglesDrawNode(Triangles source) : base(source) { } public override void ApplyState() { base.ApplyState(); shader = Source.shader; texture = Source.texture; size = Source.DrawSize; parts.Clear(); parts.AddRange(Source.parts); } public override void Draw(Action vertexAction) { base.Draw(vertexAction); if (Source.AimCount > 0 && (vertexBatch == null || vertexBatch.Size != Source.AimCount)) { vertexBatch?.Dispose(); vertexBatch = new QuadBatch(Source.AimCount, 1); } shader.Bind(); Vector2 localInflationAmount = edge_smoothness * DrawInfo.MatrixInverse.ExtractScale().Xy; foreach (TriangleParticle particle in parts) { var offset = triangle_size * new Vector2(particle.Scale * 0.5f, particle.Scale * 0.866f); var triangle = new Triangle( Vector2Extensions.Transform(particle.Position * size, DrawInfo.Matrix), Vector2Extensions.Transform(particle.Position * size + offset, DrawInfo.Matrix), Vector2Extensions.Transform(particle.Position * size + new Vector2(-offset.X, offset.Y), DrawInfo.Matrix) ); ColourInfo colourInfo = DrawColourInfo.Colour; colourInfo.ApplyChild(particle.Colour); DrawTriangle( texture, triangle, colourInfo, null, vertexBatch.AddAction, Vector2.Divide(localInflationAmount, new Vector2(2 * offset.X, offset.Y))); } shader.Unbind(); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); vertexBatch?.Dispose(); } } protected struct TriangleParticle : IComparable { /// /// The position of the top vertex of the triangle. /// public Vector2 Position; /// /// The colour shade of the triangle. /// This is needed for colour recalculation of visible triangles when or is changed. /// public float ColourShade; /// /// The colour of the triangle. /// public Color4 Colour; /// /// The scale of the triangle. /// public float Scale; /// /// Compares two s. This is a reverse comparer because when the /// triangles are added to the particles list, they should be drawn from largest to smallest /// such that the smaller triangles appear on top. /// /// /// public int CompareTo(TriangleParticle other) => other.Scale.CompareTo(Scale); } } }