Minimal example for beginners:
//In Unity3D editor, add 3D Object/Quad to Main Camera. Set quad position at (x=0 ; y=0; z=0.86;). Add current script into quad. Set window size to 512x512 or 1024x1024.
//Put raymarching_direct_compute.compute into Assets/Resources directory. Play.
using UnityEngine;
using System.Collections;
public class raymarching_direct_compute : MonoBehaviour
{
void Start ()
{
RenderTexture render_texture = new RenderTexture(1024,1024,0);
render_texture.enableRandomWrite = true;
render_texture.Create();
ComputeShader compute_shader = (ComputeShader)Resources.Load("raymarching_direct_compute");
compute_shader.SetTexture(0,"render_texture",render_texture);
compute_shader.Dispatch(0,render_texture.width/8,render_texture.height/8,1);
Renderer renderer = GetComponent<Renderer>();
renderer.material = new Material(Shader.Find("Unlit/Texture"));
renderer.material.mainTexture = render_texture;
}
}
#pragma kernel CSMain
RWTexture2D<float4> render_texture;
float sphere (float3 p,float3 c,float r)
{
return length (p-c)-r;
}
float map (float3 p)
{
return sphere (p,float3(0.0,0.0,0.0),1.0);
}
float3 set_normal (float3 p)
{
float3 x = float3 (0.01,0.00,0.00);
float3 y = float3 (0.00,0.01,0.00);
float3 z = float3 (0.00,0.00,0.01);
return normalize(float3(map(p+x)-map(p-x), map(p+y)-map(p-y), map(p+z)-map(p-z)));
}
float3 lighting ( float3 p)
{
float3 AmbientLight = float3 (0.1,0.1,0.1);
float3 LightDirection = normalize(float3(4.0,10.0,-10.0));
float3 LightColor = float3 (1.0,1.0,1.0);
float3 NormalDirection = set_normal(p);
return max ( dot(LightDirection, NormalDirection),0.0) * LightColor + AmbientLight;
}
float4 raymarch (float3 ro,float3 rd)
{
for (int i=0;i<128;i++)
{
float t = map(ro);
if (t<0.01) return float4(lighting(ro),1.0); else ro+=t*rd;
}
return float4(0.0,0.0,0.0,1.0);
}
[numthreads(8,8,1)]
void CSMain (uint2 id : SV_DispatchThreadID)
{
float2 resolution = float2 (1024,1024);
float2 coordinates = float2 (id.x,id.y);
float2 p = (2.0*coordinates.xy-resolution.xy)/resolution.y;
float3 ro = float3 (0.0,0.0,-10.0);
float3 rd = normalize( float3(p.xy,2.0));
render_texture[id] = raymarch( ro, rd );
}
Source: