Skip to content

Instantly share code, notes, and snippets.

@ArthurD
Created July 21, 2022 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArthurD/37e14c81eb257f8c3f4bd42cf2fdae4c to your computer and use it in GitHub Desktop.
Save ArthurD/37e14c81eb257f8c3f4bd42cf2fdae4c to your computer and use it in GitHub Desktop.
ReleaseAndCreateBuffer<T>
/// ....
#if SHADER_TARGET >= 45
StructuredBuffer<float4> AgentPositionData;
#endif
VertexOut vert (appdata_full v, uint instanceID : SV_InstanceID) {
#if SHADER_TARGET >= 45
float4 data = AgentPositionData[instanceID];
#else
float4 data = 0;
#endif
// ... fill in VertexOut, etc...
}
// ....
class PseudoDemo {
private ComputeBuffer InstancingBuffer;
private readonly uint[] InstancingArgs = new uint[5];
private Material AgentMaterial;
private ComputeBuffer agentPositionBuffer;
private Vector4[] agentPositionData;
private Mesh mesh;
public PseudoDemo() {
mesh = MeshHelper.CreateQuadMesh(1); // creates a mesh with 1 quad
AgentMaterial = new Material(Shader.Find(x));
ReleaseAndCreateBuffer<Vector4>(ref agentPositionData, ref agentPositionBuffer, "AgentPositionData", 16);
InstancingBuffer = new ComputeBuffer(1, InstancingArgs.Length * sizeof(uint), ComputeBufferType.IndirectArguments);
}
// Called every frame
void Tick() {
// Update Buffers
UpdateBuffers();
// This ALWAYS returns true after Setup() has been called once -- even if the buffer isn't working and/or is throwing warning ("no buffer bound, stopping draw to prevent crash") on Metal, etc...
bool isBound = AgentMaterial.HasBuffer("AgentPositionData");
// Issue occurs even if you re-bind the buffer EVERY FRAME
AgentMaterial.SetBuffer("AgentPositionData", agentPositionBuffer);
// Render
Graphics.DrawMeshInstancedIndirect(mesh, 0, AgentMaterial,
new Bounds(Vector3.zero, new Vector3(float.MaxValue, float.MaxValue, float.MaxValue)),
InstancingBuffer, 0, null,
UnityEngine.Rendering.ShadowCastingMode.Off, false,
UILevelSelector.GO_LAYER_UI, null, UnityEngine.Rendering.LightProbeUsage.Off
);
}
private void UpdateBuffers() {
InstancingArgs[0] = (uint)mesh.GetIndexCount(0);
InstancingArgs[1] = (uint)instanceCount;
InstancingArgs[2] = (uint)mesh.GetIndexStart(0);
InstancingArgs[3] = (uint)mesh.GetBaseVertex(0);
InstancingBuffer.SetData(InstancingArgs);
agentPositionBuffer.SetData(agentPositionData);
}
private void ReleaseAndCreateBuffer<T>(ref T[] bufferData, ref ComputeBuffer buffer, string bufferPropName, int bufferSize) {
// Resize metadata array
Array.Resize(ref bufferData, instanceCount);
// Release buffers & create new one of correct size
buffer?.Release();
buffer = new ComputeBuffer(instanceCount, bufferSize);
AgentMaterial.SetBuffer(bufferPropName, buffer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment