public class Voxelizer : MonoBehaviour
public ComputeShader voxelizerShader;
public PointCache pointCache;
public int resolutionX = 32;
public int resolutionY = 32;
public int resolutionZ = 32;
private RenderTexture voxelGrid;
private RenderTexture voxelCountGrid;
// Create a 3D RenderTexture for storing voxel colors
voxelGrid = new RenderTexture(resolutionX, resolutionY, 0);
voxelGrid.volumeDepth = resolutionZ;
voxelGrid.enableRandomWrite = true;
voxelGrid.format = RenderTextureFormat.ARGBFloat;
// Create a 3D RenderTexture for storing the count of points in each voxel
voxelCountGrid = new RenderTexture(resolutionX, resolutionY, 0);
voxelCountGrid.volumeDepth = resolutionZ;
voxelCountGrid.enableRandomWrite = true;
voxelCountGrid.format = RenderTextureFormat.RInt;
// Get kernel from compute shader
int kernelHandle = voxelizerShader.FindKernel("CSMain");
// Set compute shader parameters
voxelizerShader.SetInt("pointCount", pointCache.PointCount);
voxelizerShader.SetVector("minBounds", CalculateMinBounds());
voxelizerShader.SetVector("maxBounds", CalculateMaxBounds());
// Set the voxel grid textures
voxelizerShader.SetTexture(kernelHandle, "voxelGrid", voxelGrid);
voxelizerShader.SetTexture(kernelHandle, "voxelCountGrid", voxelCountGrid);
// Bind the point cloud textures
voxelizerShader.SetTexture(kernelHandle, "pointPositionsTex", pointCache.surfaces[0]); // Position texture
voxelizerShader.SetTexture(kernelHandle, "pointColorsTex", pointCache.surfaces[1]); // Color texture
// Dispatch the compute shader
voxelizerShader.Dispatch(kernelHandle, resolutionX / 8, resolutionY / 8, resolutionZ / 8);
// Normalize the voxel colors by the number of points per voxel
// Normalize the voxel colors by dividing by the number of points in each voxel
void NormalizeVoxelGrid()
int kernelHandle = voxelizerShader.FindKernel("NormalizeVoxels");
// Set the voxel grid and count grid for normalization
voxelizerShader.SetTexture(kernelHandle, "voxelGrid", voxelGrid);
voxelizerShader.SetTexture(kernelHandle, "voxelCountGrid", voxelCountGrid);
// Dispatch normalization kernel
voxelizerShader.Dispatch(kernelHandle, resolutionX / 8, resolutionY / 8, resolutionZ / 8);
// Calculate the minimum bounds of the point cloud (for normalization)
Vector3 CalculateMinBounds()
Vector3 minBounds = pointCache.pointPositions[0];
foreach (var pos in pointCache.pointPositions)
minBounds = Vector3.Min(minBounds, pos);
// Calculate the maximum bounds of the point cloud (for normalization)
Vector3 CalculateMaxBounds()
Vector3 maxBounds = pointCache.pointPositions[0];
foreach (var pos in pointCache.pointPositions)
maxBounds = Vector3.Max(maxBounds, pos);
void OnRenderImage(RenderTexture src, RenderTexture dest)
// Optionally, visualize the voxel grid by rendering it on the screen
Graphics.Blit(voxelGrid, dest);