SharpDX - How to set my vertex shader to take an instance's world matrix as input

Started by
5 comments, last by NathanRidley 10 years, 6 months ago

In the tutorials and books I've been reading so far, I've learned how to create a constant buffer and put in a world matrix as part of that buffer. The world matrix is just an identity matrix, assuming that all models in the scene are already positioned correctly in the scene. I have a simple rainbow cube and for the next step in my learning, I want to create several instances of the cube at different positions, scales and orientations. Creating the matrix for each instance is easy enough, but I'm having trouble trying to work out how to create a vertex shader that takes, as one of its inputs, the matrix representing an instance's world transform. I was under the impression that I could use any semantic name in Direct3D11, hence my use of "INSTANCE" in the code below. If I can't do that, I'm not sure what I actually need to do.

here's what my shader wrapper in C# looks like:


using SharpDX.D3DCompiler;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using Device = SharpDX.Direct3D11.Device;

namespace SharpDx4.Direct3D.Shaders
{
    public class DefaultVertexShader : ICompiledVertexShader
    {
        public DefaultVertexShader(Device device)
        {
            var shaderSource = Shaders.DefaultShaders;
            ShaderSignature signature;
            using (var bytecode = ShaderBytecode.Compile(shaderSource, "VShader", "vs_5_0"))
            {
                signature = ShaderSignature.GetInputSignature(bytecode);
                Shader = new VertexShader(device, bytecode);
            }
            var elements = new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("INSTANCE", 0, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
            };
            InputLayout = new InputLayout(device, signature, elements);
        }

        public VertexShader Shader { get; private set; }
        public InputLayout InputLayout { get; private set; }

        public void Dispose()
        {
            Shader.Dispose();
        }
    }
}

Here's the class I'm using to hold a model's buffer data:


using System;
using System.Linq;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDx4.Direct3D.Shaders;
using SharpDx4.Game.Geometry;
using Buffer = SharpDX.Direct3D11.Buffer;

namespace SharpDx4.Direct3D
{
    public class ModelDeviceData : IDisposable
    {
        public Model Model { get; set; }
        public VertexBufferBinding VerticesBufferBinding { get; set; }
        public VertexBufferBinding InstancesBufferBinding { get; set; }
        public Buffer IndicesBuffer { get; set; }
        public ICompiledVertexShader VertexShader { get; set; }
        public ICompiledPixelShader PixelShader { get; set; }
            
        public void Dispose()
        {
            VerticesBufferBinding.Buffer.Dispose();
            InstancesBufferBinding.Buffer.Dispose();
            IndicesBuffer.Dispose();
        }

        public ModelDeviceData(Model model, Device device)
        {
            Model = model;
            var vertices = Helpers.CreateBuffer(device, BindFlags.VertexBuffer, model.Vertices);
            var instances = Helpers.CreateBuffer(device, BindFlags.VertexBuffer, Model.Instances.Select(m => m.WorldMatrix).ToArray());
            VerticesBufferBinding = new VertexBufferBinding(vertices, Utilities.SizeOf<ColoredVertex>(), 0);
            InstancesBufferBinding = new VertexBufferBinding(instances, Utilities.SizeOf<Matrix>(), 0);
            IndicesBuffer = Helpers.CreateBuffer(device, BindFlags.IndexBuffer, model.Triangles);
        }
    }
}

And here's the shader code I've been mucking with.


cbuffer ConstantBuffer : register(b0)
{
    matrix World;
    matrix View;
    matrix Projection;
}

struct VIn
{
    float4 position: POSITION;
    matrix instance: INSTANCE;
    float4 color: COLOR;
};

struct VOut
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

VOut VShader(VIn input)
{
    VOut output;
    output.position = mul(input.position, input.instance);
    output.position = mul(output.position, View);
    output.position = mul(output.position, Projection);
    output.color = input.color;
    return output;
}

When I try to run this, the line which instantiates an instance of InputLayout throws the following exception:

HRESULT: [0x80070057], Module: [General], ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect.

As a beginner, obviously I'm doing something terribly wrong. Can anyone help me work out what that is? For the record I'm aware that there is such a thing as hardware instancing, but that's, like, chapter 15 in my book and I'm only up to chapter 5 so far. Yes I'm impatient, but please humour me; I'd like to get some results doing it this way first.

Advertisement

D3D11 in C++ should have same theory so I hope I can help you.

Mesh Vertices (B0) and Instance Data (B1) has to come from different buffers, as far as I can see you do have them. Next you need to bind them at once, for example B0 to slot0 and B1 to slot1. Your Input Layout has to reflect that as well, currently it says everything comes from slot0:


            var elements = new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("INSTANCE", 0, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
            };

5th argument defines in which slot data is, so you need to change it to 1 for instance data.

Thanks, though that didn't fix the problem. I tried changing my shader like so:


struct VIn
{
	float4 position: POSITION;
	float4 instance0: INSTANCE0;
	float4 instance1: INSTANCE1;
	float4 instance2: INSTANCE2;
	float4 instance3: INSTANCE3;
	float4 color: COLOR;
};

VOut VShader(VIn input)
{
	VOut output;
	matrix world = { input.instance0, input.instance1, input.instance2, input.instance3 };
	output.position = mul(input.position, world);
	output.position = mul(output.position, View);
	output.position = mul(output.position, Projection);
	output.color = input.color;
	return output;
}

And my input layout code:


var elements = new[]
{
	new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
	new InputElement("INSTANCE0", 0, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
	new InputElement("INSTANCE1", 1, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
	new InputElement("INSTANCE2", 2, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
	new InputElement("INSTANCE3", 3, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
	new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
};
InputLayout = new InputLayout(device, signature, elements);

But still no luck.

Number of observations:

When supplying a Matrix4x4 as a varying parameter, it's going to be stored as 4 float4's, so your input layout needs to reflect this (like in the second one, although breaking it explicitly is perfectly valid, but there's no reason to do so). Although it still doesn't look right, the slot and offsets are wrong, and if I understand your code correctly the order is wrong too. You have a ColoredVertex, which I assume is the Position/Color, these are in the first buffer. Then you have a second buffer with all the world matrices for each instance. It should look more like this:


var elements = new[]
{
    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0, InputClassification.PerVertexData, 0),
    new InputElement("INSTANCE", 0, Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1),
    new InputElement("INSTANCE", 1, Format.R32G32B32A32_Float, 16, 1, InputClassification.PerInstanceData, 1),
    new InputElement("INSTANCE", 2, Format.R32G32B32A32_Float, 32, 1, InputClassification.PerInstanceData, 1),
    new InputElement("INSTANCE", 3, Format.R32G32B32A32_Float, 48, 1, InputClassification.PerInstanceData, 1),
};

Note this matches the order of your two input buffers (ColorVertex in the first buffer, the Matrix in the second buffer).

And your HLSL struct:


struct VIn
{
float3 position : POSITION;
float4 color : COLOR
matrix4x4 instance : INSTANCE
};

Note you're declaring the position as R32G32B32, which is a float3. Also, all the zeros in the input layout you wanted the offset to be computed automatically? That's -1 (and SharpDX has that has a static property called AppendAligned). And of course, make sure you transpose the matrices when you write them into your buffers.

Edit:

For the input layout: the semantic name you don't need to include the index, just "INSTANCE" and you set the semantic index in the input element. Missed that when I copied the code.

Hmm, so I tried to follow your advice and I'm still getting the same exception. Is there any way to get slightly more useful information from DirectX/SharpDX as to exactly what it has a problem with?

I've uploaded my code to GitHub to make things a bit easier. The files in question are at:

https://github.com/axefrog/game-dev-learning/blob/master/SharpDx4/Direct3D/Shaders/DefaultShaders.fx

https://github.com/axefrog/game-dev-learning/blob/master/SharpDx4/Direct3D/Shaders/DefaultVertexShader.cs

https://github.com/axefrog/game-dev-learning/blob/master/SharpDx4/Direct3D/ModelDeviceData.cs

Turns out my parameter names were wrong. When setting up the InputLayout object, I should have named all four matrix rows just "INSTANCE".

Just wanted to say thanks to those who helped me sort this problem out. The results are below. I will of course keep building on this knowledge until I attain mastery smile.png

2013-11-02_1309.png

p.s. I blogged about it, for anyone who cares: http://nathanridley.com/2013/11/01/6-houston-we-have-instancing-and-animation/

This topic is closed to new replies.

Advertisement