91 lines
2.7 KiB
C#
91 lines
2.7 KiB
C#
using UnityEngine;
|
|
using System.Collections.Generic;
|
|
using Assets.WasapiAudio.Scripts.Unity;
|
|
|
|
[RequireComponent(typeof(Material))]
|
|
public class SpectrumFullscreenPassBinder : MonoBehaviour {
|
|
public WasapiAudioSource source;
|
|
|
|
private Texture2D _texture;
|
|
private Color[] _colorCache;
|
|
public Material material;
|
|
|
|
public Preferences preferences;
|
|
|
|
[SerializeReference]
|
|
[SerializeReferenceButton]
|
|
public List<SpectrumTransformer> Transformers = new List<SpectrumTransformer>();
|
|
|
|
[SpectrumDataPreview]
|
|
public SpectrumData Preview;
|
|
|
|
private void Start() {
|
|
if (source == null) {
|
|
Debug.Log("Material Binder needs WASAPI Source.");
|
|
gameObject.SetActive(false);
|
|
}
|
|
|
|
if (preferences == null) {
|
|
Debug.Log("Material Binder needs Preferences.");
|
|
gameObject.SetActive(false);
|
|
}
|
|
}
|
|
|
|
private void Update() {
|
|
UpdateTexture();
|
|
UpdateBinding();
|
|
}
|
|
|
|
private void InitialiseTexture() {
|
|
Debug.Log("Reinitialising spectrum texture...");
|
|
// material = gameObject.GetComponent<Material>();
|
|
_texture = new Texture2D(source.SpectrumSize, 1, TextureFormat.RFloat, false);
|
|
_colorCache = new Color[source.SpectrumSize];
|
|
_texture.name = $"AudioSpectrumData{source.SpectrumSize}";
|
|
}
|
|
|
|
private float[] GetSpectrumData() {
|
|
// Get raw / unmodified spectrum data
|
|
var spectrumData = source.GetSpectrumData();
|
|
|
|
// Run spectrum data through all configured transformers
|
|
if (Transformers != null && Transformers.Count > 0) {
|
|
foreach (var transformer in Transformers) {
|
|
spectrumData = transformer.Transform(spectrumData);
|
|
}
|
|
}
|
|
|
|
Preview.Values = spectrumData;
|
|
|
|
return spectrumData;
|
|
}
|
|
|
|
private void UpdateTexture() {
|
|
// init
|
|
if (_texture == null) InitialiseTexture();
|
|
|
|
var spectrumData = GetSpectrumData();
|
|
|
|
for (int i = 0; i < source.SpectrumSize; i++) {
|
|
_colorCache[i] = new Color(spectrumData[i], 0, 0, 0);
|
|
}
|
|
|
|
_texture.SetPixels(_colorCache);
|
|
_texture.Apply();
|
|
}
|
|
|
|
public void UpdateBinding() {
|
|
// !!!!
|
|
// you must set these via a literal string for some raeson
|
|
// having them as a public property didn't work
|
|
material.SetFloat("_SpectrumSize", source.SpectrumSize);
|
|
material.SetTexture("_SpectrumDataTexture", _texture);
|
|
material.SetColor("_ThemeStart", preferences.Theme().Evaluate(0.0f));
|
|
material.SetColor("_ThemeEnd", preferences.Theme().Evaluate(0.0f));
|
|
}
|
|
|
|
public string ToString() {
|
|
return "Spectrum Material Binder";
|
|
}
|
|
}
|