• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
RyxiaN

[D3D11] HLSL, StructuredBuffer and System Values

12 posts in this topic

Hi! I'm trying to create my own SpriteBatch class, actually made one a while back, but had some lousy implementation. I've seen some code around here that used a structured buffer, something like this:
[code]StructuredBuffer<Sprite> SpriteData;

struct Sprite {
float2 Position;
float2 Size;
byte TextureIndex;
};[/code]

Now, I'm not looking for help implementing this, I'm just curious if anybody know any good guides, examples or tutorials on structured buffers. I get the structured buffer thing, having one sprite struct instance per sprite. But what vertices would you send to the graphics card? I mean, if all the data you need is in the structured buffer, what would the vertices contain? They're obviously needed, else there would be nothing to process in the vertex shader. And how do you take use of the system-generated values, such as SV_InstanceID and SV_VertexID? On the samples I saw, SV_InstanceID (I think) were used to fetch the right Sprite instance from the structured buffer, but can't really get how this works.

Again: I'm not asking anyone here to help implement a SpriteBatch class/shader, only if there is any good guides or similar. Havn't found much searching around...

Thanks in advance!
0

Share this post


Link to post
Share on other sites
You might find http://software.intel.com/en-us/articles/microsoft-directcompute-on-intel-ivy-bridge-processor-graphics/ useful.
1

Share this post


Link to post
Share on other sites
[quote name='MJP' timestamp='1336069308' post='4937166']
You don't actually need any vertices or vertex buffers to render anything. You can bind a NULL vertex buffer and then say "draw 4 vertices", and then the GPU will invoke your vertex shader 4 times. Since you don't have any vertex data to pull in you typically use SV_VertexID and/or SV_InstanceID to decide what to do. Here's a really simple example of using SV_VertexID to generate a triangle that would cover the entire screen:

[code]
float4 VSMain(in uint VtxID : SV_VertexID) : SV_Position
{
float4 output = float4(-1.0f, 1.0f, 1.0f, 1.0f);

if(VtxID == 1)
output = float4(3.0f, 1.0f, 1.0f, 1.0f);
else if(VtxID == 2)
output = float4(-1.0f, -3.0f, 1.0f, 1.0f);

return output;
}
[/code]

So to invoke this you could just bind a NULL VB + IB, and call Draw with a vertex count of 3. If you want, you can also use an index buffer with a NULL vertex buffer. So for instance if you wanted to draw an indexed quad, you could have an index buffer with 6 indices that forms 2 triangles from 4 vertices. In this case SV_VertexID will give you the value from the index buffer, so in this case it would be 0 through 3. Then you could do something similar to the code above to generate one of the 4 corners of your quad for a sprite. SV_InstanceID works the same way, except it gives you the index of the instance being drawn. So in your case you would probably just use it to directly index into your structured buffer of sprite data.

Unfortunately I don't know of any good tutorials or other resources regarding structured buffers. The D3D11 book that I collaborated on (link is in my signature) has a good overview of D3D11 resource types, but that's obviously not freely available. However if you any questions I can certainly try and answer them for you.
[/quote]

Wow, this cleared up ALOT! Thanks a bunch!
To set a structured buffer, you have to create a ShaderResourceView to wrap it first? And about SV_InstanceID, you say it gives the index of the instance being drawn. What does an instance mean? Does it have to do with the draw instanced call? Havn't really looked into that yet, but if those are connected, I'll get right to it. [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img]

[quote name='Adam_42' timestamp='1336071514' post='4937182']
You might find [url="http://software.intel.com/en-us/articles/microsoft-directcompute-on-intel-ivy-bridge-processor-graphics/"]http://software.inte...essor-graphics/[/url] useful.
[/quote]

Looks very interesting! Will look more into it tomorrow when I get the time! Thanks a lot. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
0

Share this post


Link to post
Share on other sites
Wow, yet another awesome reply. Translation won't be a problem, I think. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] Yeah, instancing it is, seems to be exactly what I'm looking for. I got that working. There's just one problem, with the StructuredBuffer. I think I'm creating it right, and I think I'm setting it right aswell, but it doesn't seem to get set for some reason.

Here's some code (keep in mind it's all just for testing purposes, so it's no final code:
Shader2D.hlsl:
[code]struct Sprite {
float2 TopLeft;
float2 TopRight;
float2 BotLeft;
float2 BotRight;
float4 Color;
};

StructuredBuffer<Sprite> Sprites : register(s0);

float4 VShader(in uint VID : SV_VertexID) : SV_POSITION {
Sprite sprite = Sprites[0];

float2 pos;
if (VID == 0)
pos = float2(-1.0f, 1.0f);// sprite.TopLeft;
else if (VID == 1)
pos = float2(0.0f, 1.0f);// sprite.TopRight;
else if (VID == 2)
pos = float2(-1.0f, 0.0f);// sprite.BotLeft;
else
pos = float2(0.0f, 0.0f);// sprite.BotRight;

return float4(pos, 1.0f, 1.0f);
};



float4 PShader(in float4 position : SV_POSITION, in uint IID : SV_InstanceID) : SV_TARGET {
return Sprites[IID].Color;
}[/code]

Buffer, SRV and index buffer creation:
[code] Sprite sprite1 = new Sprite {
TopLeft = new Vector2(-1.0f, 1.0f),
TopRight = new Vector2(0.0f, 1.0f),
BotLeft = new Vector2(-1.0f, 0.0f),
BotRight = new Vector2(0.0f, 0.0f),
Color = new Vector4(1.0f, 1.0f, 0.0f, 1.0f)
};

BufferDescription bufferDescription = new BufferDescription();
bufferDescription.BindFlags = BindFlags.ShaderResource;
bufferDescription.CpuAccessFlags = CpuAccessFlags.Write;
bufferDescription.OptionFlags = ResourceOptionFlags.StructuredBuffer;
bufferDescription.SizeInBytes = MaxSprites * Sprite.SizeInBytes;
bufferDescription.StructureByteStride = Sprite.SizeInBytes;
bufferDescription.Usage = ResourceUsage.Dynamic;

using (DataStream data = new DataStream(MaxSprites * Sprite.SizeInBytes, true, true)) {
data.Write(sprite1);
data.Position = 0;

structuredBuffer = new Buffer(graphics.Device, data, bufferDescription);
}

ShaderResourceViewDescription spritesDescription = new ShaderResourceViewDescription();
spritesDescription.Dimension = ShaderResourceViewDimension.ExtendedBuffer;
spritesDescription.FirstElement = 0;
spritesDescription.Format = Format.Unknown;
spritesDescription.ElementCount = MaxSprites;
sprites = new ShaderResourceView(graphics.Device, structuredBuffer, spritesDescription);

using (DataStream dataStream = new DataStream(sizeof(uint) * 6, true, true)) {
dataStream.Write(0);
dataStream.Write(1);
dataStream.Write(2);
dataStream.Write(2);
dataStream.Write(1);
dataStream.Write(3);

dataStream.Position = 0;

indexBuffer = new Buffer(graphics.Device, dataStream, sizeof(uint) * 6, ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
}[/code]

Setting the SRV and rendering:
[code] DeviceContext context = graphics.Context;
InputAssemblerWrapper inputAssembler = context.InputAssembler;

inputAssembler.InputLayout = inputLayout;
inputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
inputAssembler.SetVertexBuffers(0, new VertexBufferBinding(null, 0, 0));
inputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);

context.PixelShader.Set(pixelShader);
context.VertexShader.Set(vertexShader);
context.VertexShader.SetShaderResource(sprites, 0);

context.DrawIndexedInstanced(6, 1, 0, 0, 0);[/code]

What I get is a black square. Should be (1.0f, 1.0f, 0.0f, 1.0f) colored. Also, if I use the points from the structured buffer, it doesnt render anything (or probably everything at (0.0f, 0.0f). So looks like the StructuredBuffer doesnt get set...

The only clear difference I see between your code and mine in the creation part is that I set srvDesc.Dimension to ExtendedBuffer instead of Buffer. I saw some other tutorial which did set it to Extended, and if I don't, the SRV won't create, returning a Direct3D11Exception.

Do I set it right? Perhaps it's something with the slot (0), in the SetShaderResource call?

[b]EDIT:[/b] Removed the qoute, was so messy. Edited by RyxiaN
0

Share this post


Link to post
Share on other sites
Hi!

[quote name='RyxiaN' timestamp='1336114904' post='4937305']
The only clear difference I see between your code and mine in the creation part is that I set srvDesc.Dimension to ExtendedBuffer instead of Buffer. I saw some other tutorial which did set it to Extended, and if I don't, the SRV won't create, returning a Direct3D11Exception.
[/quote]
AFAIK, StructuredBuffers and ByteAddressBuffers go under ExtendedBuffer, so yes, your change is correct.

I think, on the HLSL side, the shader resource view on the structured buffer should be assigned to a t-register. (s are for samplers)
[CODE]StructuredBuffer<Sprite> Sprites : register(t0); [/CODE]

Hope it helps. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
Cheers!
1

Share this post


Link to post
Share on other sites
[quote name='Tsus' timestamp='1336119456' post='4937317']
Hi!

[quote name='RyxiaN' timestamp='1336114904' post='4937305']
The only clear difference I see between your code and mine in the creation part is that I set srvDesc.Dimension to ExtendedBuffer instead of Buffer. I saw some other tutorial which did set it to Extended, and if I don't, the SRV won't create, returning a Direct3D11Exception.
[/quote]
AFAIK, StructuredBuffers and ByteAddressBuffers go under ExtendedBuffer, so yes, your change is correct.

I think, on the HLSL side, the shader resource view on the structured buffer should be assigned to a t-register. (s are for samplers)
[CODE]StructuredBuffer<Sprite> Sprites : register(t0); [/CODE]

Hope it helps. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
Cheers!
[/quote]

Made no difference. :/ Still renders black. But I still think you're right though, so I'll keep it on register(t0). :)
Thanks for the input!
0

Share this post


Link to post
Share on other sites
So, the quad is visible right?
Does it receive the right color, if you hard code it in the pixel shader?

Hm, you access the structured buffer in the pixel shader, too.
Have you bound it to the pixel shader stage as well?
[CODE]context.PixelShader.SetShaderResource(sprites, 0);[/CODE]

Besides, I think the SV_InstanceID is input to the vertex shader, not the pixel shader. You could as well read the color in the vertex shader and pass it by to the pixel shader.

Cheers! Edited by Tsus
1

Share this post


Link to post
Share on other sites
[quote name='Tsus' timestamp='1336123632' post='4937326']
So, the quad is visible right?
Does it receive the right color, if you hard code it in the pixel shader?

Hm, you access the structured buffer in the pixel shader, too.
Have you bound it to the pixel shader stage as well?
[CODE]context.PixelShader.SetShaderResource(sprites, 0);[/CODE]

Besides, I think the SV_InstanceID is input to the vertex shader, not the pixel shader. You could as well read the color in the vertex shader and pass it by to the pixel shader.

Cheers!
[/quote]

Wow, so stupid. No I hadn't bound it to the pixel shader. [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img] And yeah, apparantly SV_InstanceID wasn't sent to the pixel shader. Now it works like a charm! Time to mess around a little. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

Thank you both!

[b]EDIT[/b]: Is binding a resource very time consuming? I assume they are already on the GPU so shouldn't be much right? Edited by RyxiaN
0

Share this post


Link to post
Share on other sites
[quote name='RyxiaN' timestamp='1336126144' post='4937333']
Is binding a resource very time consuming? I assume they are already on the GPU so shouldn't be much right?
[/quote]

It depends very, very much on the hardware, but in general you should minimize state changes. E.g. when binding a resource the caches are invalidated and several things are validated (are all mipmaps available (for textures), have the formats changed etc). Probably even worth is changing a shader, since it internally changes much more states, potentially invalidating various caches (including the texture cache) as well as inlining of functions in case you use dynamic shader linkage etc.

Writing a system that keeps on the CPU side track of the states and binds them when you submit a draw or dispatch call, isn’t worth it btw, since the GPU already does that for you. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

We have many experts here in the forum, so if you open up a new topic, you can get much more (and better [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]) information on this.
2

Share this post


Link to post
Share on other sites
[quote name='Tsus' timestamp='1336131666' post='4937346']
[quote name='RyxiaN' timestamp='1336126144' post='4937333']
Is binding a resource very time consuming? I assume they are already on the GPU so shouldn't be much right?
[/quote]

It depends very, very much on the hardware, but in general you should minimize state changes. E.g. when binding a resource the caches are invalidated and several things are validated (are all mipmaps available (for textures), have the formats changed etc). Probably even worth is changing a shader, since it internally changes much more states, potentially invalidating various caches (including the texture cache) as well as inlining of functions in case you use dynamic shader linkage etc.

Writing a system that keeps on the CPU side track of the states and binds them when you submit a draw or dispatch call, isn’t worth it btw, since the GPU already does that for you. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

We have many experts here in the forum, so if you open up a new topic, you can get much more (and better [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]) information on this.
[/quote]

Allright. :) I think I'll just leave it to the experts for now. x) Doubt it will make a difference anyway. My biggest thought were more if it was worth binding the StructuredBuffer to both the vertex shader and the pixel shader, or just send along the variables from the vertex shader to the pixel shader through parameters with semantics, which I think I'll end up doing instead. :)
0

Share this post


Link to post
Share on other sites
Binding a resource is going to be almost entirely CPU overhead. You'll pay some cost for the managed/native transition, for making the underlying D3D call, and possibly some driver overhead. In terms of GPU performance, it's likely that accessing the color in the vertex shader will be cheaper than accessing it in the pixel shader. This is because doing it in the vertex shader means you'll only pay for the memory access 4 times, instead of once for each pixel rendered.

At any rate, these performance differences are going to be very small unless you render a LOT of sprites.
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0