WebGPU Render Primitives Not Working

I’m trying to get Graphics.RenderPrimitivesIndexedIndirect to work in a Web build using the WebGPU graphics api. I have managed to get Graphics.RenderMesh to work, but none of the render primitives methods seem to work. By this I mean, the objects display when running in the editor, but not in the web build.

I have used the chrome extension WebGPU Inspector and from a capture can see that there are zero draw calls coming from the Graphics.RenderPrimitivesIndexedIndirect call. In fact, if I remove all meshes from the scene I can clearly see there are no opaque draws at all.

So my first question is, do the render primitive methods work at all for WebGPU?

My follow up question being, if they do work, what am I doing wrong?

Here’s the full script which sets up the compute shader and the draw call. Sorry, it’s very messy, I’ve just been messing around today.

using System.Collections.Generic;
using Unity.Collections;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.Rendering;

public class PolygonManager : MonoBehaviour
{
    /*
    The purpose of this MonoBehaviour is to read the positions associated with an
    array of line renderers and pass them to a compute buffer which
    computes an extrusion of each 2d shape lying along the xz plane defined by
    each line renderer.

    
    */
    private struct SourceShape
    {
        public int pointsBufferOffset;
        public int pointsBufferSize;
        public override string ToString()
        {
            return string.Format("{0} <= x < {1}", pointsBufferOffset, pointsBufferOffset + pointsBufferSize);
        }
    }

    private struct SourcePoint
    {
        public float3 position;
    }

    private struct DebugInfo
    {
        public int success;
        public int errorCode;

        public override string ToString()
        {
            string[] errors = new string[]
            {
                "None",
                "Dequeue failure",
                "Enqueue failure",
                "Ear clipping failed to resolve",
                "Ear clipping terminated incorrectly",
                "Not enough points",
                "Queue overflow"
            };
            return string.Format("Result {0} - {1}",
                success.ToString() + "/" + (success == 1 ? "Failure" : success == 2 ? "Success" : "Unknown"),
                errorCode.ToString() + "/" + (errorCode < 0 ? "UNDEFINED [< 0]" : errorCode >= errors.Length ? "UNDEFINED [OUT OF ARRAY BOUNDS]" : errors[errorCode])
            );
        }
    }

    [SerializeField]
    private LineRenderer[] lineRenderers;

    [SerializeField]
    private ComputeShader triangulationComputeShader = default;
    [SerializeField]
    private Material material = default;


    // Buffers
    private ComputeBuffer sourcePointsBuffer;
    private ComputeBuffer sourceShapesBuffer;
    private ComputeBuffer drawVertexBuffer;
    private GraphicsBuffer drawIndexBuffer;
    private GraphicsBuffer computeIndexBuffer;
    private GraphicsBuffer argsBuffer;
    private ComputeBuffer debugInfoBuffer;
    private ComputeBuffer wallFaceNormalBuffer;
    private ComputeBuffer heightsBuffer;

    // Misc 
    private int idTriangulationKernel;
    private int dispatchSize;
    private Bounds combinedBounds;

    // Buffer strides

    private const int SOURCE_SHAPE_STRIDE = sizeof(int) * 2;
    private const int SOURCE_POINT_STRIDE = sizeof(float) * 3;
    private const int DRAW_VERTEX_STRIDE = sizeof(float) * 3 * 2;
    private const int DEBUG_INFO_STRIDE = sizeof(int) * 2;
    private const int WALL_FACE_STRIDE = sizeof(float) * 3;


    // Start is called once before the first execution of Update after the MonoBehaviour is created
    private void OnEnable()
    {
        SourceShape[] sourceShapes = new SourceShape[lineRenderers.Length];
        List<SourcePoint> sourcePointsList = new List<SourcePoint>();
        GraphicsBuffer.IndirectDrawIndexedArgs[] args = new GraphicsBuffer.IndirectDrawIndexedArgs[lineRenderers.Length];
        int pointOffset;
        combinedBounds = lineRenderers[0].bounds;
        DebugInfo[] debugDetails = new DebugInfo[lineRenderers.Length];

        // Loop over the line renderers
        for (int j = 0; j < lineRenderers.Length; j++)
        {
            LineRenderer lineRenderer = lineRenderers[j];

            //  Prepopulate debug details to verify they are changed by the compute shader
            debugDetails[j] = new DebugInfo
            {
                success = 99,
                errorCode = 99
            };
            // Update point offset
            pointOffset = sourcePointsList.Count;

            // Grow bounds
            combinedBounds.Encapsulate(lineRenderer.bounds);

            // Copy line renderer positions to native array
            NativeArray<Vector3> positions = new NativeArray<Vector3>(lineRenderer.positionCount, Allocator.Temp);
            lineRenderer.GetPositions(positions);

            // Loop over positions
            for (int i = 0; i < positions.Length; i++)
            {
                sourcePointsList.Add(new SourcePoint { position = (float3)positions[i] });
            }
            // Construct shape struct to hold offset and length info for buffer
            sourceShapes[j] = new SourceShape
            {
                pointsBufferOffset = pointOffset,
                pointsBufferSize = positions.Length
            };
            // Construct draw args for shapes draw command
            args[j] = new GraphicsBuffer.IndirectDrawIndexedArgs
            {
                indexCountPerInstance = (uint)(sourceShapes[j].pointsBufferSize * 2 - 2) * 6,
                instanceCount = 1,
                startIndex = (uint)(sourceShapes[j].pointsBufferOffset * 2 - 2 * j) * 6,
                baseVertexIndex = 0,
                startInstance = 0
            };
        }

        sourceShapesBuffer = new ComputeBuffer(lineRenderers.Length, SOURCE_SHAPE_STRIDE, ComputeBufferType.Structured, ComputeBufferMode.Immutable);
        sourceShapesBuffer.SetData(sourceShapes);

        debugInfoBuffer = new ComputeBuffer(lineRenderers.Length, DEBUG_INFO_STRIDE, ComputeBufferType.Structured, ComputeBufferMode.Immutable);
        debugInfoBuffer.SetData(debugDetails);

        sourcePointsBuffer = new ComputeBuffer(sourcePointsList.Count, SOURCE_POINT_STRIDE, ComputeBufferType.Structured, ComputeBufferMode.Immutable);
        sourcePointsBuffer.SetData(sourcePointsList);

        drawVertexBuffer = new ComputeBuffer(sourcePointsList.Count, DRAW_VERTEX_STRIDE, ComputeBufferType.Structured, ComputeBufferMode.Immutable);

        // The next buffer creation is likely redundant
        // It has been added along with a buffer copy
        // just in case the WebGPU build was failing due
        // to incompatibility with an index buffer marked
        // structured.  I think this is just a DX11 issue
        // though

        // Compute shader writes to this (Structured only)
        computeIndexBuffer = new GraphicsBuffer(
            GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource,
            (sourcePointsList.Count * 2 - sourceShapes.Length * 2) * 6,
            sizeof(uint)
        );

        // Rendering reads from this (Index only)
        drawIndexBuffer = new GraphicsBuffer(
            GraphicsBuffer.Target.Index | GraphicsBuffer.Target.CopyDestination,
            (sourcePointsList.Count * 2 - sourceShapes.Length * 2) * 6,
            sizeof(uint)
        );

        wallFaceNormalBuffer = new ComputeBuffer(sourcePointsList.Count * 2, WALL_FACE_STRIDE, ComputeBufferType.Structured, ComputeBufferMode.Immutable);
        heightsBuffer = new ComputeBuffer(sourceShapes.Length, sizeof(float), ComputeBufferType.Structured, ComputeBufferMode.Dynamic);
        heightsBuffer.SetData(new float[] { 5, 10 });


        argsBuffer = new GraphicsBuffer(GraphicsBuffer.Target.IndirectArguments, sourceShapes.Length, GraphicsBuffer.IndirectDrawIndexedArgs.size);
        argsBuffer.SetData(args);

        idTriangulationKernel = triangulationComputeShader.FindKernel("Main");

        // Set buffers for compute shader
        triangulationComputeShader.SetBuffer(idTriangulationKernel, "_SourcePoints", sourcePointsBuffer);
        triangulationComputeShader.SetBuffer(idTriangulationKernel, "_SourceShapes", sourceShapesBuffer);
        triangulationComputeShader.SetBuffer(idTriangulationKernel, "_DrawVertexes", drawVertexBuffer);
        triangulationComputeShader.SetBuffer(idTriangulationKernel, "_DrawIndexes", computeIndexBuffer);
        triangulationComputeShader.SetBuffer(idTriangulationKernel, "_DebugDetails", debugInfoBuffer);
        triangulationComputeShader.SetBuffer(idTriangulationKernel, "_WallFaceNormals", wallFaceNormalBuffer);
        triangulationComputeShader.SetInt("_NumShapes", lineRenderers.Length);

        // Determine dispatch size
        triangulationComputeShader.GetKernelThreadGroupSizes(idTriangulationKernel, out uint threadGroupSize, out _, out _);
        dispatchSize = Mathf.CeilToInt((float)lineRenderers.Length / threadGroupSize);
    }

    private void OnDisable()
    {
        sourcePointsBuffer.Release();
        sourceShapesBuffer.Release();
        drawVertexBuffer.Release();
        drawIndexBuffer.Release();
        argsBuffer.Release();
    }

    // Update is called once per frame
    private void LateUpdate()
    {
        Debug.Log($"Dispatching {dispatchSize} thread groups for {lineRenderers.Length} shapes");
        triangulationComputeShader.Dispatch(idTriangulationKernel, dispatchSize, 1, 1);

        Graphics.CopyBuffer(computeIndexBuffer, drawIndexBuffer);

        // Probably not needed, added just to see if it would fix WebGPU issue
#if UNITY_WEBGL
        CommandBuffer cmd = new CommandBuffer();
        cmd.name = "Compute-Graphics Barrier";
        Graphics.ExecuteCommandBuffer(cmd);
        cmd.Release();
#endif

        // Commented out calls to various debug functions which print results of compute shader

        // AsyncGPUReadback.Request(debugInfoBuffer, DebugInfoCallback);
        // AsyncGPUReadback.Request(drawIndexBuffer, DrawIndexCallback);
        // AsyncGPUReadback.Request(drawVertexBuffer, DrawVertexCallback);
        // AsyncGPUReadback.Request(wallFaceNormalBuffer, WallFaceNormalCallback);

        // Modulate height of extrusions for interest
        float[] heights = new float[lineRenderers.Length];
        for (int i = 0; i < lineRenderers.Length; i++)
        {
            heights[i] = Mathf.Sin(Time.realtimeSinceStartup * (i + 13) / 10f) * 7f;
        }
        heightsBuffer.SetData(heights);


        // Render each shape as its own instance
        RenderParams rp = new RenderParams(material);
        rp.shadowCastingMode = ShadowCastingMode.Off;
        rp.worldBounds = new Bounds(new Vector3(), new Vector3(100000, 100000, 100000));
        rp.matProps = new MaterialPropertyBlock();

        // Assign buffers
        rp.matProps.SetBuffer("_DrawVertexes", drawVertexBuffer);
        rp.matProps.SetBuffer("_SourceShapes", sourceShapesBuffer);
        rp.matProps.SetBuffer("_WallFaceNormals", wallFaceNormalBuffer);
        rp.matProps.SetBuffer("_Heights", heightsBuffer);

        // Draw all shapes with multi-draw indirect
        Graphics.RenderPrimitivesIndexedIndirect(
            rp,
            MeshTopology.Triangles,
            drawIndexBuffer,
            argsBuffer,
            lineRenderers.Length
        );
    }

    private void DebugInfoCallback(AsyncGPUReadbackRequest req)
    {
        Debug.Log("Callback on GPU read");
        NativeArray<DebugInfo> result = req.GetData<DebugInfo>();
        for (int i = 0; i < result.Length; i++)
        {
            Debug.LogFormat("Got result: {0}", result[i]);
        }
    }

    private void DrawIndexCallback(AsyncGPUReadbackRequest req)
    {
        Debug.Log("Callback on GPU read");
        NativeArray<int> result = req.GetData<int>();
        string indexes = "";
        for (int i = 0; i < result.Length; i++)
        {
            indexes += result[i].ToString() + ",";

        }
        Debug.LogFormat("Indexes: {0}", indexes);
    }

    private void DrawVertexCallback(AsyncGPUReadbackRequest req)
    {
        Debug.Log("Callback on GPU read");
        NativeArray<float3> result = req.GetData<float3>();
        string indexes = "";
        for (int i = 0; i < result.Length; i++)
        {
            indexes += result[i].ToString() + ",";

        }
        Debug.LogFormat("Vertexes: {0}", indexes);
    }

    private void WallFaceNormalCallback(AsyncGPUReadbackRequest req)
    {
        Debug.Log("Callback on GPU read");
        NativeArray<float3> result = req.GetData<float3>();
        string indexes = "";
        for (int i = 0; i < result.Length; i++)
        {
            indexes += result[i].ToString() + ",";

        }
        Debug.LogFormat("Wall face normals: {0}", indexes);
    }
}

I did a quick sanity test based on the RenderPrimitivesIndexedIndirect in the unity docs and that worked (after fixing what I see is a bug in the doc sample, I should report that).

So to answer question 1, yes it’s supported.
The follow up question is trickier. I assume since you’re using the Inspector you also don’t see any errors in the console. I’m not sure what you’re doing wrong from the script. You definitely don’t need to do that “Compute-Graphics Barrier” thing, that’s not needed. If you have it as a small project you could DM me, I’d be happy to poke it with a stick, see if I can figure it out.

Thanks, yes, there are no console errors. Before I waste your time, I’ll do the same as you and test the docs example, in both my project, and a brand new one. It is a very light weight project, as it only contains the above script and a few other shader scripts.

The project was setup using 6000.1.x and then upgraded to 6000.3.x and is using URP. I am wondering if I have some settings wrong.

Also, the compute shader that is dispatched is definitely computing the draw data correctly as I output that for testing and it seems fine.

Something I am doing, is using a custom function in the shadergraph to fetch the vertex data in the vertex part of the shader. It could maybe be problematic? Although in saying that, I tested the shader with RenderMesh rather than RenderPrimitives and it seemed fine, also I cannot see how it could cause the draw call not to happen at all. For reference, here is the custom function script:

#ifndef UNITY_INDIRECT_DRAW_ARGS
#define UNITY_INDIRECT_DRAW_ARGS IndirectDrawIndexedArgs
#include "UnityIndirect.cginc"
#endif

// This describes a vertex on the generated mesh
struct DrawVertex {
    float3 positionWS; // Position in world space
};

// struct DrawTriangle {
//     float3 normalWS; // normal in world space. All points share this normal
//     DrawVertex vertices[3];
// };

struct SourceShape {
    uint pointBufferOffset;
    uint pointBufferSize;
};

struct FaceNormal {
    float3 normalWS; // normal in world space. All points share this normal
};


// The buffer to draw from
StructuredBuffer<DrawVertex> _DrawVertexes;
StructuredBuffer<SourceShape> _SourceShapes;
StructuredBuffer<FaceNormal> _WallFaceNormals;
StructuredBuffer<float> _Heights;

void GetVertexData_float(float vertexId, out float3 position, out float2 texcoord, out float3 normal)
{
    uint commandID;
    uint instanceCount;
    #ifndef SHADERGRAPH_PREVIEW
        InitIndirectDrawArgs(0);
        commandID = GetCommandID(0);
        instanceCount = GetIndirectInstanceCount();
    #else
        commandID = 0;
        instanceCount = 1;
    #endif
    
    const uint vertIndex = (uint)round(vertexId);

    uint vertType = vertIndex/_SourceShapes[commandID].pointBufferSize;
    uint rawVertIndex = vertIndex%_SourceShapes[commandID].pointBufferSize + _SourceShapes[commandID].pointBufferOffset;

    const float height = _Heights[commandID];

    float3 normals[6] = {
        float3(0.0,1.0,0.0),
        float3(0.0,-1.0,0.0),
        -_WallFaceNormals[rawVertIndex*2].normalWS,
        -_WallFaceNormals[rawVertIndex*2].normalWS,
        -_WallFaceNormals[rawVertIndex*2+1].normalWS,
        -_WallFaceNormals[rawVertIndex*2+1].normalWS
    };
    
    float3 heightOffsets[2];
    heightOffsets[0] = float3(0.0,height*0.5+abs(height)*0.5,0.0);
    heightOffsets[1] = float3(0.0,height*0.5-abs(height)*0.5,0.0);

    DrawVertex input = _DrawVertexes[rawVertIndex];

    position = input.positionWS + heightOffsets[vertType%2];
    normal = normals[vertType];
    texcoord = float2(0,0); // placeholder

    // uint vid = (uint)vertexId % 3;
    
    // float3 positions[3] = {
    //     float3(0, 0, 0),
    //     float3(1, 0, 0),
    //     float3(0, 1, 0)
    // };
    
    // position = positions[vid];
    // normal = float3(0, 0, 1);
    // texcoord = float2(0, 0);
}