using UnityEngine; using System.Collections; public class ComputeShaderOutput : MonoBehaviour { public ComputeShader computeShader; public const int VertCount = 10 * 10 * 10 * 10 * 10 * 10; public ComputeBuffer outputBuffer; public Shader pointShader; Material PointMaterial; public bool debugRender = false; int CSKernel; void InitializeBuffers() { outputBuffer = new ComputeBuffer(VertCount, (sizeof(float) * 3) + (sizeof(int) * 6)); if (debugRender) PointMaterial.SetBuffer("buf_Points", outputBuffer); } public void Dispatch() { if(!SystemInfo.supportsComputeShaders) { Debug.LogWarning("Compute Shaders Not Supported"); return; } computeShader.Dispatch(CSKernel, 10, 10, 10); } public void ReleaseBuffers() { outputBuffer.Release(); } void Start () { CSKernel = computeShader.FindKernel("CSMain"); if (debugRender) { PointMaterial = new Material(pointShader); PointMaterial.SetVector("_worldPos", transform.position); } InitializeBuffers(); } void OnRenderObject() { if (debugRender) { Dispatch(); PointMaterial.SetPass(0); PointMaterial.SetVector("_worldPos", transform.position); Graphics.DrawProcedural(MeshTopology.Points, VertCount); } } private void OnDisable() { ReleaseBuffers(); } }
ComputeShaderOutput
// Each #kernel tells which function to compile; you can have many kernels #pragma kernel CSMain #define thread_group_size_x 10 #define thread_group_size_y 10 #define thread_group_size_z 10 #define group_size_x 10 #define group_size_y 10 #define group_size_z 10 struct positionStruct { float3 pos; } RWStructuredBuffer<positionStruct> outputBuffer; [numthreads(thread_group_size_x, thread_group_size_y, thread_group_size_z] [numthreads(8,8,1)] void CSMain (uint3 grpID : SV_GroupID, uint3 id : SV_DispatchThreadID, uint3 grpTID : SV_GroupThreadID, uint grpIDX : SV_GroupIndex) { int idx = id.x + (id.y * thread_group_size_x * group_size_x) + (id.z * thread_group_size_x * group_size_y * thread_group_size_y * group_size_z); float scale = 0.5f; float pos = (id + grpTID + grpID * float3(thread_group_size_x, thread_group_size_y, thread_group_size_z))); outputBuffer[idx].pos = pos * scale; }
Grid Generator.compute
Shader "Unlit/PointShader" { SubShader { Pass { CGPROGRAM #pragma target 5.0 #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct data { float3 pos; }; //The buffer StructuredBuffer<data> buf_Points; float3 _worldPos; //input Struct struct ps_input { float4 pos: SV_POSITION; float3 color: COLOR0; }; ps_input vert(uint id : SV_VertexID) { ps_input o; float3 worldPos = buf_Points[id].pos + _worldPos; o.pos = mul(UNITY_MATRIX_VP, float4(worldPos,1.0f)); o.color = worldPos; return o; } float4 frag(ps_input i) : COLOR { float4 col = float4(i.color,1); if (i.color.r <= 0 && i.color.g <= 0 && i.color.b <= 0) { col.rgb = float3(0,1,1); } return col; } ENDCG } } Fallback Off }
PointShader
http://www.emersonshaffer.com/blog/2016/5/11/unity3d-compute-shader-introduction-tutorial