Posts

Showing posts from July, 2021

Compute Shader, read from calculated buffer

 Use case - get the GPU to calculate a bunch of X,Y,Z coordinates for an arbitrary number of instanced prefabs in Unity.  On the Unity C# side, we need : To specify a compute shader, a handle for the compute shader, a buffer that we'll be writing to in the shader, a prefab, the number of prefabs we want, an array for the instanced prefabs, an array for the coordinate data. Any extra variables we want to pass over, eg time. On the compute shader side we need : To specify a read-write buffer, instead of a texture that we created in the previous post. The buffer will be of float3 type, which is how HLSL calls a vector3. That's actually it... Here's the Compute Shader code - #pragma kernel boxMove RWStructuredBuffer<float3> yesBlad; float time; [numthreads(64,1,1)] void boxMove (uint3 id : SV_DispatchThreadID) {     float xpos = (float)id.x;     float ypos = sin(id.x+time)*50;     float zpos = cos(id.x +time)* 50;     float3 pos = { xpos,ypos,zpos };          yesBlad[id.x

Compute Shader, absolute minimum

 First make a compute shader - right click in the project window-  create shader, compute shader The default code will look as follows // Each #kernel tells which function to compile; you can have many kernels #pragma kernel CSMain // Create a RenderTexture with enableRandomWrite flag and set it // with cs.SetTexture RWTexture2D<float4> Result; [numthreads(8,8,1)] void CSMain (uint3 id : SV_DispatchThreadID) {     // TODO: insert actual code here!     Result[id.xy] = float4(id.x & id.y, (id.x & 15)/15.0, (id.y & 15)/15.0, 0.0); }   To keep things simple, lets just replace that last Result... line with    Result[id.xy]=float4(1,1,0,0);  This will make our shader produce a yellow colour. Note the #pragma kernel is called CSMain. This is basically the function name we'll be calling from the C# script.   To go with the compute shader, we need a C# script that assigns the shader to our geometry. Let's use a Quad as our test geo. Again, in the project window, create

Step function (HLSL)

 step(edge,x)   this will return 1 if the 2nd argument (x) is greater or equal to  the first (edge). 0 is returned if this is false.