soundvision/UnityProject/Assets/Editor/SpectrumGenerator.cs

51 lines
1.5 KiB
C#
Raw Normal View History

2019-09-29 10:00:16 +00:00
using UnityEngine;
namespace cylvester
{
interface ISpectrumGenerator
{
Texture2D Spectrum { get; }
2019-09-29 17:47:17 +00:00
int Update(float[] fftData, ref Rect selectionRect);
2019-09-29 10:00:16 +00:00
}
public class SpectrumGenerator : ISpectrumGenerator
{
private Texture2D texture_;
public Texture2D Spectrum => texture_;
public SpectrumGenerator(int width, int height)
{
texture_ = new Texture2D(width, height);
}
2019-09-29 17:47:17 +00:00
public int Update(float[] fftData, ref Rect selectionRect)
2019-09-29 10:00:16 +00:00
{
2019-09-29 17:47:17 +00:00
var numPixels = 0;
2019-09-29 16:04:26 +00:00
for (var x = 0; x < texture_.width; x++)
2019-09-29 10:00:16 +00:00
{
2019-09-29 17:47:17 +00:00
var magnitude = fftData[x] * 20f;
2019-09-29 16:04:26 +00:00
for (var y = 0; y < texture_.height; y++)
2019-09-29 10:00:16 +00:00
{
2019-09-29 17:47:17 +00:00
var mY = texture_.height - selectionRect.y;
2019-09-29 16:04:26 +00:00
2019-09-29 17:47:17 +00:00
var fillPixel = magnitude > y;
var color = fillPixel ? Color.green : Color.black;
2019-09-29 10:00:16 +00:00
if ((selectionRect.x < x && x < (selectionRect.x + selectionRect.width)) &&
2019-09-29 17:47:17 +00:00
(mY - selectionRect.height < y && y < mY))
2019-09-29 10:00:16 +00:00
{
2019-09-29 17:47:17 +00:00
color.a = 1f;
if (fillPixel)
numPixels++;
2019-09-29 10:00:16 +00:00
}
2019-09-29 17:47:17 +00:00
else
{
color.a = 0.2f;
}
texture_.SetPixel(x, y, color);
2019-09-29 10:00:16 +00:00
}
}
texture_.Apply();
2019-09-29 17:47:17 +00:00
return numPixels;
2019-09-29 10:00:16 +00:00
}
}
}