From 3378a181a89e6e97159ad37feaf5adfa5cdc6724 Mon Sep 17 00:00:00 2001 From: Stedd Date: Sun, 8 Oct 2023 02:17:41 +0200 Subject: [PATCH] passing a variable to the shader --- Assets/Scripts/ComputeController.cs | 29 +++++++++++++++++++++++++--- Assets/Shaders/ColorInverter.compute | 7 +++---- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/Assets/Scripts/ComputeController.cs b/Assets/Scripts/ComputeController.cs index 1e4c162..f28e8b4 100644 --- a/Assets/Scripts/ComputeController.cs +++ b/Assets/Scripts/ComputeController.cs @@ -15,12 +15,20 @@ public class ComputeController : MonoBehaviour [SerializeField] private float _scale = 1; [SerializeField] private bool _resize; + [Header("state")] + [SerializeField] private float sin; + private int _kernelHandle; + private const int NumThreadX = 8; + private const int NumThreadY = 8; + + #region ShaderVariables + private static readonly int Result = Shader.PropertyToID("result"); private static readonly int SourceTexture = Shader.PropertyToID("source_texture"); + private static readonly int SinScaled = Shader.PropertyToID("sin_scaled"); - private static readonly int _threadgroupX = 8; - private static readonly int _threadgroupY = 8; + #endregion private void Start() { @@ -42,16 +50,31 @@ public class ComputeController : MonoBehaviour _computeShader.SetTexture(_kernelHandle, SourceTexture, _inputTexture); _computeShader.SetTexture(_kernelHandle, Result, _resultTexture); - _computeShader.Dispatch(_kernelHandle, _width / _threadgroupX, _height / _threadgroupY, 1); + DispatchShader(); + } + + private void DispatchShader() + { + _computeShader.Dispatch(_kernelHandle, _width / NumThreadX, _height / NumThreadY, 1); } private void OnGUI() { CheckScale(); + + ShaderUpdate(); + GUI.DrawTexture(new Rect(0, 0, _width, _height), _inputTexture); GUI.DrawTexture(new Rect(0, _height, _width, _height), _resultTexture); } + private void ShaderUpdate() + { + sin = (Mathf.Sin(Time.unscaledTime) + 1) / 2; + _computeShader.SetFloat(SinScaled, sin); + DispatchShader(); + } + private void CheckScale() { if (_resize) diff --git a/Assets/Shaders/ColorInverter.compute b/Assets/Shaders/ColorInverter.compute index 0987c18..1b23b3d 100644 --- a/Assets/Shaders/ColorInverter.compute +++ b/Assets/Shaders/ColorInverter.compute @@ -1,15 +1,14 @@ #pragma kernel cs_main -// The output texture +Texture2D source_texture; RWTexture2D result; -// Input texture -Texture2D source_texture; +float sin_scaled; [numthreads(8, 8, 1)] void cs_main(uint3 id : SV_DispatchThreadID) { float4 color = source_texture[id.xy]; - color.rgb = 1 - color.rgb; + color.rgb = color.rgb * sin_scaled * 2; result[id.xy] = color; }