using System; using System.Drawing; using Azimuth; using Blacklight.Core; using Glass; using Glass.Blacklight; using Prism; using Prism.Glass; namespace Konis.Testbed { /// /// A texture that plots a function from 0 to 1 along its width, with the material that draws it. /// public class FunctionPlot { /// /// The color behind the plot. /// public static readonly Prism.Color Background = Prism.Color.FromArgb(255, 20, 22, 28); /// /// The color of the lines that mark where the function is 0 and where it is 1. /// public static readonly Prism.Color Guide = Prism.Color.FromArgb(255, 62, 66, 80); /// /// The color of the function's own line. /// public static readonly Prism.Color Line = Prism.Color.FromArgb(255, 255, 200, 90); /// /// The colors a plot is drawn in. /// public static readonly PlotColors Colors = new PlotColors { Background = Background, Guide = Guide, Line = Line, }; // What a def with no function over life has, which is one everywhere. private static readonly IScalarFunction One = new PiecewiseLinear((0, 1)); private readonly WindowHandle window; private readonly Texture texture; private readonly byte[] pixels; private readonly int width; private readonly int height; /// /// Makes a plot by pixels, which shows nothing until it is /// given a function. /// /// The width is under 2, or the height is under 1. public FunctionPlot(WindowHandle window, int width, int height) { this.window = window ?? throw new ArgumentNullException(nameof(window)); CheckWidth(width); this.width = width; this.height = height; pixels = new byte[Rgba.ByteCount(width, height)]; texture = window.CreateDynamicTexture(new DecodedImage(pixels, new Size(width, height))); Material = new TextureMaterial { Texture = new BlacklightGlassTexture { Texture = texture } }; } /// /// Gets the material that draws the plot. /// public Glass.Material Material { get; } private static void CheckWidth(int width) { if (width < 2) { throw new ArgumentOutOfRangeException(nameof(width), width, "A plot needs at least two columns."); } } /// /// Draws into . The plot spans 0 to 1 up the height at /// least, and grows to hold what else the function reaches. A null function draws as the constant one, and a /// value that isn't finite leaves a gap. /// /// The width is under 2, or the height is under 1. /// The buffer isn't the size of the plot. public static void Draw(byte[] pixels, int width, int height, IScalarFunction function) { IScalarFunction shown = function ?? One; CheckWidth(width); FunctionPlotter.Draw(pixels, width, height, shown, FunctionPlotter.RangeOf(shown, width), Colors); } /// /// Replaces the plot's pixels, which must be pixels and as many as the plot has. /// public void Upload(byte[] rgba) { window.UpdateTexture(texture, rgba); } /// /// Draws a function into the plot, or the constant one when it is null. /// public void Show(IScalarFunction function) { Draw(pixels, width, height, function); Upload(pixels); } } }