72 lines
2.1 KiB
C#
72 lines
2.1 KiB
C#
using UnityEngine;
|
|
using System.Collections.Generic;
|
|
using Assets.WasapiAudio.Scripts.Unity;
|
|
|
|
[RequireComponent(typeof(Material))]
|
|
public class ThemeShaderBinder : MonoBehaviour
|
|
{
|
|
public Material material;
|
|
public Preferences preferences;
|
|
|
|
private Texture2D _texture;
|
|
private Color[] _colorCache;
|
|
private int textureSize = 128;
|
|
private Gradient _theme;
|
|
|
|
private void Start() {
|
|
if (preferences == null) {
|
|
Debug.Log("Theme Shader Binder needs Preferences.");
|
|
gameObject.SetActive(false);
|
|
}
|
|
}
|
|
|
|
private void Update() {
|
|
UpdateTexture();
|
|
UpdateBinding();
|
|
}
|
|
|
|
public Color DecomposeHdrColor(Color linearColorHdr) {
|
|
var maxColorComponent = linearColorHdr.maxColorComponent;
|
|
float scaleFactor = 191f / maxColorComponent;
|
|
float exposure = Mathf.Log(255f / scaleFactor) / Mathf.Log(2f);
|
|
float factor = 1f / exposure;
|
|
|
|
if (exposure <= 1f) {
|
|
return linearColorHdr;
|
|
}
|
|
|
|
float r = linearColorHdr.r * factor;
|
|
float g = linearColorHdr.g * factor;
|
|
float b = linearColorHdr.b * factor;
|
|
|
|
return new Color(r, g, b, linearColorHdr.a);
|
|
}
|
|
|
|
private void UpdateTexture() {
|
|
if (_theme == preferences.Theme()) return;
|
|
|
|
Debug.Log("Reinitialising Theme texture...");
|
|
_texture = new Texture2D(textureSize, 1);
|
|
_theme = preferences.Theme();
|
|
_colorCache = new Color[textureSize];
|
|
_texture.name = $"ThemeTexture{textureSize}";
|
|
_texture.wrapMode = TextureWrapMode.Clamp;
|
|
|
|
for (int i = 0; i < textureSize; i++) {
|
|
if (_theme == null) return;
|
|
Color color = DecomposeHdrColor(_theme.Evaluate((float)i / (float)textureSize));
|
|
// Color color = _theme.Evaluate((float)i / (float)textureSize);
|
|
_colorCache[i] = color;
|
|
}
|
|
|
|
_texture.SetPixels(_colorCache);
|
|
_texture.Apply();
|
|
}
|
|
|
|
public void UpdateBinding() {
|
|
UpdateTexture();
|
|
material.SetFloat("_ThemeSize", textureSize);
|
|
material.SetTexture("_ThemeTexture", _texture);
|
|
}
|
|
}
|